使用註解配置spring+junit 測試
阿新 • • 發佈:2019-01-24
使用註解配置spring
步驟:
1、導包:4+2+spring-aop
2、為主配置檔案引入新的名稱空間(約束)
3、開啟使用註解代理配置檔案
<!-- 指定掃描cn.itcast.bean報下的所有類中的註解.
注意:掃描包時.會掃描指定報下的所有子孫包
-->
<context:component-scan base-package="cn.itcast.bean"></context:component-scan>
4、在類中使用註解完成配置
將物件註冊到容器
@Component("user") @Service("user") // service層 @Controller("user") // web層 @Repository("user")// dao層
修改物件的作用範圍
//指定物件的作用範圍
@Scope(scopeName="singleton")
ps:測試一下不同的作用域singleton和prototype的區別
demo如下:
public class Demo { @Test public void fun1(){ //1 建立容器物件 ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //2 向容器"要"user物件 User u1 = (User) ac.getBean("user"); User u2 = (User) ac.getBean("user"); System.out.println(u1==u2); //3 列印user物件 System.out.println(u1); ac.close(); } }
測試結果:
這是初始化
true
User [name=tom, age=18, car=Car [name=附加迪威龍, color=綠色]]
這是銷燬
修改範圍:
//指定物件的作用範圍
@Scope(scopeName="prototype")
測試結果:
這是初始化
這是初始化
false
User [name=tom, age=18, car=Car [name=附加迪威龍, color=綠色]]
這裡稍微寫一下兩者區別:
這裡的scope就是用來配置spring bean的作用域,它標識bean的作用域。
-
1、singleton 當把一個bean定義設定為singleton作用域時,Spring IOC容器只會建立該bean定義的唯一例項
-
2、prototype prototype作用域部署的bean,每一次請求(將其注入到另一個bean中,或者以程式的方式呼叫容器的getBean()方法)都會產生一個新的bean例項,相當於一個new的操作。
簡單的說:
singleton 只有一個例項,也即是單例模式。
prototype訪問一次建立一個例項,相當於new。
一般情況下,有狀態的bean需要使用prototype模式,而對於無狀態的bean一般採用singleton模式(一般的dao都是無狀態的)。
狀態場景:
每次呼叫bean的方法,singleton多次呼叫bean實際上使用的是同一個singleton物件,而且儲存了物件的狀態資訊。prototype都會提供一個新的物件(重新new),並不儲存原有的例項。
值型別注入
-------------通過反射的Field賦值,破壞了封裝性:
@Value("tom")
private String name;
-----------通過set方法賦值,推薦使用:
@Value("tom")
public void setName(String name) {
this.name = name;
}
引用型別注入
//@Autowired //自動裝配
//問題:如果匹配多個型別一致的物件.將無法選擇具體注入哪一個物件.
//@Qualifier("car2")//使用@Qualifier註解告訴spring容器自動裝配哪個名稱的物件
@Resource(name="car")//手動注入,指定注入哪個名稱的物件(重點)
private Car car;
初始化和銷燬方法
@PostConstruct //在物件被建立後呼叫.init-method
public void init(){
System.out.println("我是初始化方法!");
}
@PreDestroy //在銷燬之前呼叫.destory-method
public void destory(){
System.out.println("我是銷燬方法!");
}
spring與junit整合測試
一、導包:4+2+aop+test
二、配置註解和測試
//幫我們建立容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定建立容器時使用哪個配置檔案
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
//將名為user的物件注入到u變數中
@Resource(name="user")
private User u;
@Test
public void fun1(){
System.out.println(u);
}
}
上圖: