(六)Spring详解——使用注解替代配置文件

首先
修改applicationContext.xml文件
加入命名空间以支持注解
xmlns:context=”http://www.springframework.org/schema/context”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
然后

    <!-- 注册注解的后台处理类 -->
    <context:annotation-config>
    <!-- 指明使用注解的类的包 -->
    <context:component-scan base-package="com.shinerio.domain"/>

类上添加注解,交给Spring维护
@Component(“goods”) //通用方式,不推荐使用
public class Goods {}
@Repository、@Service、@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。
依赖注入
可以加载属性上,也可以加载set方法和构造方法上
@Autowired默认按类型自动装配
@Autowired@Qualifier(“bean的名字例如goods”)按名字自动装配
加在构造方法上时@Qualifier加在参数前面
作用域注解
加在类上
@Scope(“singleton,prototype,request,session”)
支持JSR-250 定义注解
@Resource
@Resource 的作用相当于 @Autowired,只不过 @Autowired 按 byType 自动注入,面@Resource 默认按 byName 自动注入
@Resource 有两个属性是比较重要的,分别是 name 和 type,Spring 将@Resource 注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型
Resource 注解类位于 Spring 发布包的 lib/j2ee/common-annotations.jar 类包中。
@PostConstruct 和 @PreDestroy
Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,您既可以通过实现 InitializingBean/DisposableBean 接口来定制初始化之后 / 销毁之前的操作方法,也可以通过 <bean> 元素的 init-method/destroy-method 属性指定初始化之后 / 销毁之前调用的操作方法
JSR-250 为初始化之后/销毁之前方法的指定定义了两个注释类,分别是 @PostConstruct 和 @PreDestroy,这两个注释只能应用于方法上。标注了 @PostConstruct 注释的方法将在类实例化后调用,而标注了 @PreDestroy 的方法将在类销毁之前调用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值