8.2 Spring的”零配置”支持
8.2.1搜索Bean類
- @Component:標註一個普通的Spring Bean類
(@Component(“abc”):指定bean類實例的名稱爲abc) - @Controler:標註一個控制器組件類
- @Service:標註一個業務邏輯組件類
- @Repository:標註一個DAO組件類
//需要在配置文件中指定Spring搜索路徑
<beans>
...
<context:component-scan base-package="ustc.gr.service"/>
...
</beans>
PS:
//指定所有以Chinese結尾的類被當做Spring Bean處理
<beans>
...
<context:include-filter type="regex" expression=".*Chinese"/>
...
</beans>
8.2.2 指定Bean的作用域
@Scope("prototype")
@Component("login")
public class Login{
...
}
8.2.3 @Resource配置
類似配置文件中的ref
@Computent
public class login{
private Axe axe;
//***********
@Resource(name="stoneAx")
public void setAxe(Axe axe){
this.axe = axe;
}
....
}
@Resource可以直接修飾實例變量,可以省略set方法,
@Computent
public class login{
//***********
@Resource(name="stoneAx")
private Axe axe;
....
}
8.2.4 @PostConstrut (初始化方法)與@PreDestroy (銷燬之前執行的fan)
@Computent
public class login{
@Resource(name="stoneAx")
private Axe axe;
//Bean的依賴注入完成之後執行
@PostConstrut
public void myInit(){
。。。
}
//Bean銷燬之前執行
@PreDestroy
public void myClodse(){
。。。
}
}