首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Spring诠注注入

2012-10-09 
Spring注解注入1、古老的注入方式:实现类:/** * @title UserServiceImpl.java * @description UserService

Spring注解注入
1、古老的注入方式:
实现类:

/** * @title UserServiceImpl.java * @description UserService实现类 * @author cao_xhu * @version * @create_date Oct 30, 2009 * @copyright (c) CVIC SE */public class UserServiceImpl implements UserService {private UserDAO userDAO;public void setUserDAO(UserDAO userDAO) {this.userDAO = userDAO;}...}

配置文件:
<bean id="userDAO" /></property></bean><bean id="userServiceImpl"/></property></bean>


2、使用注解的方式:
2.1、Autowired注解
<1>对成员变量注解
实现类:
@Autowiredprivate IndustryDao industryDao;...

<2>set方法注解
@Autowiredpublic void setDao(IndustryDao industryDao){super.setDao(industryDao);}

配置文件:

<!-- 使用 <context:annotation-config/> 简化配置Spring 2.1 添加了一个新的 context 的 Schema 命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。 而我们前面所介绍的 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor 就是处理这些注释元数据的处理器。但是直接在 Spring 配置文件中定义这些 Bean 显得比较笨拙。Spring 为我们提供了一种方便的注册这些 BeanPostProcessor 的方式,这就是 <context:annotation-config/>。 --><context:annotation-config /><bean id="industryDao"/><bean id="industryService"/>


@Autowired可以对成员变量、方法和构造函数进行标注,来完成自动注入。
@Autowired的标注位置不同,它们都会在Spring在初始化industryService这个bean时,自动装配industryDao这个属性,区别是:第一种实现中,Spring会直接将IndustryDao类型的唯一一个bean赋值给industryDao这个成员变量;第二种实现中,Spring会调用setDao方法来将IndustryDao类型的唯一一个bean装配到industryDao这个属性。

2.2、@Qualifier
@Autowired是根据类型进行自动注入的,如果spring配置文件中存在多个IndustryDao类型的bean时,或者不存在IndustryDao类型的bean,都会抛出异常。
存在多个类型的实例时,按id注入@Qualifier("core.system.hibernateService")
HibernateService hibernateService;@Autowiredpublic void setHibernateService(@Qualifier("core.system.hibernateService")HibernateService hibernateService){this.hibernateService = hibernateService;}

若不存在某类型的实例:告诉 Spring:在找不到匹配 Bean 时也不报错

@Autowired(required = false)public void setHibernateService(@Qualifier("core.system.hibernateService")HibernateService hibernateService){this.hibernateService = hibernateService;}

2.3、使用 JSR-250 的注解
<1> @Resource
spring支持@Resource、@PostConstruct以及@PreDestroyJSR-250的标准注解。
@Resource可以按type注入,也可以按name注入。@Resource默认按byName自动注入。
Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。

@Resource装配顺序
如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
如果既没有指定name,又没有指定type,则自动按照byName方式进行装配(见2);如果没有匹配,则回退为一个原始类型(UserDao)进行匹配,如果匹配则自动装配;
<2> @PostConstruct 和 @PreDestroy
Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,您既可以通过实现 InitializingBean/DisposableBean 接口来定制初始化之后 / 销毁之前的操作方法,也可以通过 <bean> 元素的 init-method/destroy-method 属性指定初始化之后 / 销毁之前调用的操作方法。
JSR-250 为初始化之后/销毁之前方法的指定定义了两个注释类,分别是 @PostConstruct 和 @PreDestroy,这两个注释只能应用于方法上。标注了 @PostConstruct 注释的方法将在类实例化后调用,而标注了 @PreDestroy 的方法将在类销毁之前调用。

使用 @PostConstruct 和 @PreDestroy 注释的 Boss.java
package com.baobaotao;import javax.annotation.Resource;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;public class Boss {    @Resource    private Car car;    @Resource(name = "office")    private Office office;    @PostConstruct    public void postConstruct1(){        System.out.println("postConstruct1");    }    @PreDestroy    public void preDestroy1(){        System.out.println("preDestroy1");     }    …}


测试类代码:
package com.baobaotao;import org.springframework.context.support.ClassPathXmlApplicationContext;public class AnnoIoCTest {    public static void main(String[] args) {        String[] locations = {"beans.xml"};        ClassPathXmlApplicationContext ctx =             new ClassPathXmlApplicationContext(locations);        Boss boss = (Boss) ctx.getBean("boss");        System.out.println(boss);        ctx.destroy();// 关闭 Spring 容器,以触发 Bean 销毁方法的执行    }}

标注了 @PostConstruct 的 postConstruct1() 方法将在 Spring 容器启动时,创建 Boss Bean 的时候被触发执行,而标注了 @PreDestroy 注释的 preDestroy1() 方法将在 Spring 容器关闭前销毁 Boss Bean 的时候被触发执行。

3、使用 @Component
虽然我们可以通过 @Autowired 或 @Resource 在 Bean 类中使用自动注入功能,但是 Bean 还是在 XML 文件中通过 <bean> 进行定义 —— 也就是说,在 XML 配置文件中定义 Bean,通过 @Autowired 或 @Resource 为 Bean 的成员变量、方法入参或构造函数入参提供自动注入的功能。能否也通过注释定义 Bean,从 XML 配置文件中完全移除 Bean 定义的配置呢?答案是肯定的,我们通过 Spring 2.5 提供的 @Component 注释就可以达到这个目标了。

下面,我们完全使用注释定义 Bean 并完成 Bean 之间装配:
使用 @Component 注释的Woman.java
@Componentpublic class Woman{    …}


使用 @Component 注释的Woman.java
@Componentpublic class Man{    …}

这样,我们就可以在 Human类中通过 @Autowired 注入前面定义的 Woman和 Man Bean 了。

@Component("human")public class Human{    @Autowired    private Woman woman;    @Autowired    private Man man;    …}


一般情况下,Bean 都是 singleton 的,需要注入 Bean 的地方仅需要通过 byType 策略就可以自动注入了,所以大可不必指定 Bean 的名称。如果需要使用其它作用范围的 Bean,可以通过 @Scope 注释来达到目标:
@Scope("prototype")@Component("human")public class Human{       …}


在使用 @Component 注释后,Spring 容器必须启用类扫描机制以启用注释驱动 Bean 定义和注释驱动 Bean 自动注入的策略。Spring 2.5 对 context 命名空间进行了扩展,提供了这一功能,请看下面的配置:
<?xml version="1.0" encoding="UTF-8" ?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-2.5.xsd">    <context:component-scan base-package="springlive.learn.component "/></beans>



参考资料:
使用 Spring 2.5 注释驱动的 IoC 功能http://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/?ca=drs-tp0808

热点排行