Spring ioc注解教程

 

目录

一、         概述... 4

二、         具体介绍... 5

1.     传统写法... 5

1.1.      介绍... 5

1.2.      实例... 5

2.     Annotation注解... 7

2.1.      @Autowired. 7

2.2.      @Autowired(required = false). 9

2.3.      @Qualifier. 10

2.4.      @Resource. 12

2.5.      @PostConstruct @PreDestroy. 13

2.6.      <context:annotation-config/>. 14

2.7.      @Component. 15

2.8.      <context:component-scan/>. 17

2.9.      @Scope. 17

三、         总结... 18

 

一、        概述

注释配置相对于 XML 配置具有很多的优势:

  • 它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作。如使用 JPA 注释配置 ORM 映射时,我们就不需要指定 PO 的属性名、类型等信息,如果关系表字段和 PO 属性名、类型都一致,您甚至无需编写任务属性映射信息——因为这些信息都可以通过 Java 反射机制获取。
  • 注释和 Java 代码位于一个文件中,而 XML 配置采用独立的配置文件,大多数配置信息在程序开发完成后都不会调整,如果配置信息和 Java 代码放在一起,有助于增强程序的内聚性。而采用独立的 XML 配置文件,程序员在编写一个功能时,往往需要在程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。

因此在很多情况下,注释配置比 XML 配置更受欢迎,注释配置有进一步流行的趋势。Spring 2.5 的一大增强就是引入了很多注释类,现在您已经可以使用注释配置完成大部分 XML 配置的功能。在这篇文章里,我们将向您讲述使用注释进行 Bean 定义和依赖注入的内容。

  

我们通常是采用spring xml配置文件的方式进行bean注入,从而完成beanbean直接的相互依赖关系的。如下是 3 个类,它们分别是 OfficeCar Boss,这 3 个类需要在 Spring 容器中配置为 Bean

1.2.             实例

package com.baobaotao;

public class Office {

    private String officeNo =”001”;

 

    //省略 get/setter

 

    @Override

    public String toString() {

        return "officeNo:" + officeNo;

    }

}

其中Office中拥有一个属性officeNo

 

package com.baobaotao;
 
public class Car {
    private String brand;
    private double price;
 
    // 省略 get/setter
 
    @Override
    public String toString() {
        return "brand:" + brand + "," + "price:" + price;
    }
}

其中Car中拥有两个个属性brandprice

 

package com.baobaotao;
 
public class Boss {
    private Car car;
    private Office office;
 
    // 省略 get/setter
 
    @Override
    public String toString() {
        return "car:" + car + "\n" + "office:" + office;
    }
}
 

其中Boss中拥有Car类型的属性carOffice类型的属性office

 

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="boss" class="com.baobaotao.Boss">
        <property name="car" ref="car"/>
        <property name="office" ref="office" />
    </bean>
    <bean id="office" class="com.baobaotao.Office">
        <property name="officeNo" value="002"/>
    </bean>
    <bean id="car" class="com.baobaotao.Car" scope="singleton">
        <property name="brand" value=" 红旗 CA72"/>
        <property name="price" value="2000"/>
    </bean>
</beans>
 

此配置文件为在 Spring 容器中将 Office Car 声明为 Bean,并注入到 Boss Bean

2.       Annotation注解

2.1.             @Autowired

2.1.1.        介绍

Spring 2.5 引入了@Autowired注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作

2.1.2.       实例
package com.baobaotao;
import org.springframework.beans.factory.annotation.Autowired;
 
public class Boss {
 
    @Autowired
    private Car car;
 
    @Autowired
    private Office office;
 
    
}
 

使用 @Autowired 注释的 Boss.java

 

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <!--  BeanPostProcessor 将自动起作用,对标注 @Autowired  Bean 进行自动注入 -->
    <bean class="org.springframework.beans.factory.annotation.
        AutowiredAnnotationBeanPostProcessor"/>
 
    <!-- 移除 boss Bean 的属性注入配置的信息 -->
    <bean id="boss" class="com.baobaotao.Boss"/>
    <bean id="office" class="com.baobaotao.Office">
        <property name="officeNo" value="001"/>
    </bean>
    <bean id="car" class="com.baobaotao.Car" scope="singleton">
        <property name="brand" value=" 红旗 CA72"/>
        <property name="price" value="2000"/>
    </bean>
</beans>
 

Spring 通过一个BeanPostProcessor@Autowired进行解析,所以要让@Autowired起作用必须事先在 Spring 容器中声明AutowiredAnnotationBeanPostProcessor Bean

这样,当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有@Autowired注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。

按照上面的配置,Spring 将直接采用 Java 反射机制对 Boss 中的caroffice这两个私有成员变量进行自动注入。所以对成员变量使用@Autowired后,您大可将它们的 setter 方法(setCar()setOffice())从 Boss 中删除。

 

package com.baobaotao;
 
public class Boss {
    private Car car;
    private Office office;
 
     @Autowired
    public void setCar(Car car) {
        this.car = car;
    }
    @Autowired
    public void setOffice(Office office) {
        this.office = office;
    }
    
}
 

@Autowired将查找被标注的方法的入参类型的 Bean,并调用方法自动注入这些 Bean

 

package com.baobaotao;
 
public class Boss {
    private Car car;
    private Office office;
    @Autowired
    public Boss(Car car ,Office office){
        this.car = car;
        this.office = office ;
    }
    
}
 

由于Boss()构造函数有两个入参,分别是caroffice@Autowired将分别寻找和它们类型匹配的 Bean,将它们作为Boss(Car car ,Office office)的入参来创建Boss Bean

 

 

2.2.             @Autowired(required = false)

2.2.1.        介绍

在默认情况下使用@Autowired注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出BeanCreationException异常,并指出必须至少拥有一个匹配的 Bean

在默认情况下使用@Autowired注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出BeanCreationException异常,并指出必须至少拥有一个匹配的 Bean

2.2.2.       实例
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd ">
    <bean class="org.springframework.beans.factory.annotation.
        AutowiredAnnotationBeanPostProcessor"/> 
 
    <bean id="boss" class="com.baobaotao.Boss"/>
 
    <!--  office Bean 注释掉 -->
    <!-- <bean id="office" class="com.baobaotao.Office">
    <property name="officeNo" value="001"/>
    </bean>-->
 
    <bean id="car" class="com.baobaotao.Car" scope="singleton">
        <property name="brand" value=" 红旗 CA72"/>
        <property name="price" value="2000"/>
    </bean>
</beans>
 

由于office Bean 被注释掉了,所以 Spring 容器中将没有类型为Office Bean 了,而 Boss office属性标注了@Autowired,当启动 Spring 容器时,异常就产生了。

 

package com.baobaotao;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
 
public class Boss {
 
    private Car car;
    private Office office;
 
    @Autowired
    public void setCar(Car car) {
        this.car = car;
    }
    @Autowired(required = false)
    public void setOffice(Office office) {
        this.office = office;
    }
    
}
 

当不能确定 Spring 容器中一定拥有某个类的 Bean 时,可以在需要自动注入该类 Bean 的地方可以使用@Autowired(required = false),这等于告诉 Spring:在找不到匹配 Bean 时也不报错。

2.3.             @Qualifier

2.3.1.        介绍

如果 Spring 容器中拥有多个候选 BeanSpring 容器在启动时也会抛出BeanCreationException异常。

Spring 允许我们通过@Qualifier注释指定注入 Bean 的名称。

2.3.2.       实例
               
<bean id="office" class="com.baobaotao.Office">
    <property name="officeNo" value="001"/>
</bean>
<bean id="office2" class="com.baobaotao.Office">
    <property name="officeNo" value="001"/>
</bean>
 

我们在 Spring 容器中配置了两个类型为Office类型的 Bean,当对 Boss office成员变量进行自动注入时,Spring 容器将无法确定到底要用哪一个 Bean,因此异常发生了。

 

   @Autowired
public void setOffice(@Qualifier("office")Office office) {
    this.office = office;
}
 

@Qualifier("office")中的office Bean 的名称,所以@Autowired@Qualifier结合使用时,自动注入的策略就从 byType 转变成 byName 了。@Autowired可以对成员变量、方法以及构造函数进行注释,而@Qualifier的标注对象是成员变量、方法入参、构造函数入参。正是由于注释对象的不同,所以 Spring 不将@Autowired@Qualifier统一成一个注释类。

 

 public class Boss {
    @Autowired
    private Car car;
    @Autowired
    @Qualifier("office")
    private Office office;
    
}

对成员变量使用 @Qualifier 注释

 

public class Boss {
    private Car car;
    private Office office;
 
    @Autowired
    public Boss(Car car , @Qualifier("office")Office office){
        this.car = car;
        this.office = office ;
          }
}

对构造函数变量使用 @Qualifier 注释

 

@Qualifier只能和@Autowired结合使用,是对@Autowired有益的补充。一般来讲,@Qualifier对方法签名中入参进行注释会降低代码的可读性,而对成员变量注释则相对好一些。

2.4.             @Resource

2.4.1.        介绍

@Resource 的作用相当于 @Autowired,只不过 @Autowired byType 自动注入,面 @Resource 默认按 byName 自动注入罢了。@Resource 有两个属性是比较重要的,分别是 name typeSpring @Resource 注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略。

    Resource
注释类位于 Spring 发布包的 lib/j2ee/common-annotations.jar 类包中,因此在使用之前必须将其加入到项目的类库中。

2.4.2.       实例
package com.baobaotao;
 
import javax.annotation.Resource;
 
public class Boss {
    // 自动注入类型为 Car  Bean
    @Resource
    private Car car;
 
    // 自动注入 bean 名称为 office  Bean
    @Resource(name = "office")
    private Office office;
}
 

一般情况下,我们无需使用类似于@Resource(type=Car.class)的注释方式,因为 Bean 的类型信息可以通过 Java 反射从代码中获取。

 

<bean 
  class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>

一般情况下,我们无需使用类似于@Resource(type=Car.class)的注释方式,因为 Bean 的类型信息可以通过 Java 反射从代码中获取。

CommonAnnotationBeanPostProcessor实现了BeanPostProcessor接口,它负责扫描使用了 JSR-250 注释的 Bean,并对它们进行相应的操作。

2.5.            @PostConstruct @PreDestroy

2.5.1.        介绍

Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,您既可以通过实现 InitializingBean/DisposableBean 接口来定制初始化之后 / 销毁之前的操作方法,也可以通过 <bean> 元素的 init-method/destroy-method 属性指定初始化之后 / 销毁之前调用的操作方法

JSR-250 为初始化之后/销毁之前方法的指定定义了两个注释类,分别是 @PostConstruct @PreDestroy,这两个注释只能应用于方法上。标注了 @PostConstruct 注释的方法将在类实例化后调用,而标注了 @PreDestroy 的方法将在类销毁之前调用。

 

2.5.2.       实例
               
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"); 
    }
    
}
 

您只需要在方法前标注@PostConstruct@PreDestroy,这些方法就会在 Bean 初始化后或销毁之前被 Spring 容器执行了。

我们知道,不管是通过实现InitializingBean/DisposableBean接口,还是通过 <bean> 元素的init-method/destroy-method属性进行配置,都只能为 Bean 指定一个初始化 / 销毁的方法。但是使用@PostConstruct@PreDestroy注释却可以指定多个初始化 / 销毁方法,那些被标注@PostConstruct@PreDestroy注释的方法都会在初始化 / 销毁时被执行。

 

2.6.            <context:annotation-config/>

2.6.1.        介绍

Spring 2.1 添加了一个新的 context Schema 命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。

而我们前面所介绍的AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor就是处理这些注释元数据的处理器。但是直接在 Spring 配置文件中定义这些 Bean 显得比较笨拙。Spring 为我们提供了一种方便的注册这些BeanPostProcessor的方式,这就是 <context:annotation-config/>

2.6.2.       实例
<?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:annotation-config/> 
 
    <bean id="boss" class="com.baobaotao.Boss"/>
    <bean id="office" class="com.baobaotao.Office">
        <property name="officeNo" value="001"/>
    </bean>
    <bean id="car" class="com.baobaotao.Car" scope="singleton">
        <property name="brand" value=" 红旗 CA72"/>
        <property name="price" value="2000"/>
    </bean>
</beans>
 

<context:annotationconfig/> 将隐式地向 Spring 容器注册AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessorPersistenceAnnotationBeanPostProcessor以及equiredAnnotationBeanPostProcessor 4 BeanPostProcessor

在配置文件中使用 context 命名空间之前,必须在 <beans> 元素中声明 context 命名空间。

2.7.            @Component

2.7.1.        介绍

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

2.7.2.       实例
package com.baobaotao;
 
import org.springframework.stereotype.Component;
 
@Component
public class Car {
    
}
 

使用 @Component 注释的 Car.java

 

package com.baobaotao;
 
import org.springframework.stereotype.Component;
 
@Component
public class Office {
    private String officeNo = "001";
    
}
 

使用 @Component 注释的 Office.java

 

package com.baobaotao;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
 
@Component("boss")
public class Boss {
    @Autowired
    private Car car;
 
    @Autowired
    private Office office;
    
}

@Component有一个可选的入参,用于指定 Bean 的名称,在 Boss 中,我们就将 Bean 名称定义为boss。一般情况下,Bean 都是 singleton 的,需要注入 Bean 的地方仅需要通过 byType 策略就可以自动注入了,所以大可不必指定 Bean 的名称。

 

<?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="com.baobaotao"/>
</beans>
 

在使用@Component注释后,Spring 容器必须启用类扫描机制以启用注释驱动 Bean 定义和注释驱动 Bean 自动注入的策略。Spring 2.5 context 命名空间进行了扩展,提供了这一功能。

所有通过 <bean> 元素定义 Bean 的配置内容已经被移除,仅需要添加一行 <context:component-scan/> 配置就解决所有问题了——Spring XML 配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注释形式存在罢了)。<context:component-scan/> base-package 属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。

2.8.            <context:component-scan/>

2.8.1.        介绍

<context:component-scan/>还允许定义过滤器将基包下的某些类纳入或排除。Spring 支持以下 4 种类型的过滤方式,通过下表说明:

过滤器类型

说明

注释

假如 com.baobaotao.SomeAnnotation 是一个注释类,我们可以将使用该注释的类过滤出来。

类名指定

通过全限定类名进行过滤,如您可以指定将 com.baobaotao.Boss 纳入扫描,而将 com.baobaotao.Car 排除在外。

正则表达式

通过正则表达式定义过滤的类,如下所示: com\.baobaotao\.Default.*

AspectJ 表达式

通过 AspectJ 表达式定义过滤的类,如下所示: com. baobaotao..*Service+

2.8.2.       实例
<context:component-scan base-package="com.baobaotao">
    <context:include-filter type="regex" 
        expression="com\.baobaotao\.service\..*"/>
    <context:exclude-filter type="aspectj" 
        expression="com.baobaotao.util..*"/>
</context:component-scan>

值得注意的是 <context:component-scan/> 配置项不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor),因此当使用 <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了。

2.9.            @Scope

2.9.1.        介绍

默认情况下通过@Component定义的 Bean 都是 singleton 的,如果需要使用其它作用范围的 Bean,可以通过@Scope注释来达到目标.

2.9.2.       实例
package com.baobaotao;
import org.springframework.context.annotation.Scope;
@Scope("prototype")
@Component("boss")
public class Boss {
    
}

这样,当从 Spring 容器中获取boss Bean 时,每次返回的都是新的实例了。

 

 

三、        总结

是否有了这些 IOC 注释,我们就可以完全摒除原来 XML 配置的方式呢?答案是否定的。有以下几点原因:

  • 注释配置不一定在先天上优于 XML 配置。如果 Bean 的依赖关系是固定的,(如 Service 使用了哪几个 DAO 类),这种配置信息不会在部署时发生调整,那么注释配置优于 XML 配置;反之如果这种依赖关系会在部署时发生调整,XML 配置显然又优于注释配置,因为注释是对 Java 源代码的调整,您需要重新改写源代码并重新编译才可以实施调整。
  • 如果 Bean 不是自己编写的类(如 JdbcTemplate、SessionFactoryBean 等),注释配置将无法实施,此时 XML 配置是唯一可用的方式。
  • 注释配置往往是类级别的,而 XML 配置则可以表现得更加灵活。比如相比于 @Transaction 事务注释,使用 aop/tx 命名空间的事务配置更加灵活和简单。

所以在实现应用中,我们往往需要同时使用注释配置和 XML 配置,对于类级别且不会发生变动的配置可以优先考虑注释配置;而对于那些第三方类以及容易发生调整的配置则应优先考虑使用 XML 配置。Spring 会在具体实施 Bean 创建和 Bean 注入之前将这两种配置方式的元信息融合在一起。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值