【Spring笔记】(四) 8.2 Spring的零配置支持

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(){
        。。。
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章