Spring 學習筆記(五)IOC之零註解配置(用註解代替applicationContext.xml配置檔案)
阿新 • • 發佈:2018-12-16
有了這個東西開發方便很多,不用寫xml那些配置嘍。
package org.spring.exampleAOP; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; /** * spring 配置類 */ @Configuration @ComponentScan(value = {"org.spring.exampleAOP"}) //註解掃描 @PropertySource(value="classpath:my.properties") //載入配置檔案 //@Import(value={SpringConfig.class}) // 匯入多個配置類 對於properties public class SpringConfig {
@Configuration 代表這個類是spring的配置類
@ComponentScan 要掃描的包
@PropertySource 載入配置檔案
@Import 匯入多個配置檔案(配置檔案得是被@PropertySource描述過的class)
初始化ApplicationContext(就獲取方式不一樣, 其他呼叫都一樣)
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
@Bean註解
這個註解挺有意思,首先會執行被描述的方法,然後把方法的返回值物件塞到IOC容器裡;如果方法沒有返回值的話會報錯 “ needs to have a non-void return type!”。
@Bean和@Resource/@Autowried是反著的, @Resource是取出來,@Bean是存進去。
特意測試了一下@Bean的其他情況:
測試程式碼:
- 當有多個方法的返回值物件型別一樣的話, 那麼只會執行最上面的這個方法。
- 如果這個返回值的型別被@Component它們註釋,也是不執行的,也就是說@Bean的級別比@Component的級別高。
@Component public class Kazhafei implements People { public Kazhafei() { System.out.println("構造:卡扎菲初始化"); } @Override public void getPeopleName() { System.out.println("我是卡扎菲"); } }
@Component //相當於bean標籤, beanName預設首字母小寫
@Scope("singleton") //等同bean標籤中的scope
public class Sadamu implements People {
public Sadamu() {
System.out.println("構造:薩達姆初始化");
}
@Bean(name = "kazhafei")
public Kazhafei getKazhafeiBean2() {
System.out.println("getKazhafeiBean2");
return new Kazhafei();
}
/**
* 會執行方法
* 並把方法的返回物件放入IOC容器
* */
@Bean(name = "kazhafei")
public Kazhafei getKazhafeiBean() {
System.out.println("getKazhafeiBean");
return new Kazhafei();
}
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
System.out.println("-----------------IOC初始化完畢-------------------");
//獲取Bean物件
Sadamu people1 = (Sadamu) applicationContext.getBean("sadamu");
}
}
執行結果:
構造:薩達姆初始化
getKazhafeiBean2
構造:卡扎菲初始化
-----------------IOC初始化完畢-------------------
Process finished with exit code 0