集成struts2 spring hibernate中使用注解

大家知道利用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容器的关闭而被调用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值