集成struts2 spring hibernate中使用注解

来源:互联网 发布:淘宝卖家跑哪去了 编辑:程序博客网 时间:2024/05/22 11:31

大家知道利用struts,spring,hibernate进行开发时候,需要配置很多的XML文件。使用注解可以减少XML文件的配置。

Spring 使用注解方式自动扫描对象纳入Spring管理容器:

首先:

在Spring配置文件中启动自动扫描功能, 并指定其扫描范围:

<!-- 让Spring知道如何查找加入annotation的bean -->
<context:component-scan base-package="cn.com.*" />

分为4类注解:

@Controller 用于标注控制层, 即MVC的C;

@Service 用于标注业务逻辑层, 即BIZ, Service

@Repository 用于标注数据访存层对象, 即DAO

@Component 当对象无法归类时使用

Bean的作用域设置: 以上四类默认为单例模式

@Scope("prototype"); 将模式修改为原型模式

例子: 一个业务逻辑层的Bean

@Service("testService") //testService为bean名称
@Scope("prototype")     //将作用域调整为原型, 不加此注解默认为单例
public class TestServiceBean implements TestService {

    private TestDao dao;

    public void setDao(TestDao dao) {
        this.dao = dao;
    }
   
}

Spring容器的每个Bean具有初始化方法和销毁方法的配置
<bean init-method="初始化方法" destroy-method="销毁方法"></bean>
如何使用注解的方式实现呢?


@Service("testService") //testService为bean名称
@Scope("prototype")     //将作用域调整为原型, 不加此注解默认为单例
public class TestServiceBean implements TestService {
   
    private TestDao dao;
   
    @PostConstruct
    public void init() {}
   
    @PreDestroy
    public void destroy() {}

   
    public void setDao(TestDao dao) {
        this.dao = dao;
    }
}

注: init方法是在对象初始化后被自动调用, destroy方法在Spring容器的关闭而被调用。

原创粉丝点击