Spring 详解Java的Spring框架中的注解的用法

这篇文章主要介绍了Java的Spring框架中的注解的用法,包括对Java bean的定义的作用介绍,需要的朋友可以参考下

1. 使用Spring注解来注入属性

1.1. 使用注解以前我们是怎样注入属性的 
类的实现:

?

1

2

3

4

5

6

7

classUserManagerImpl implementsUserManager {

  privateUserDao userDao;

  publicvoid  setUserDao(UserDao userDao) {

    this.userDao = userDao;

  }

  ...

}

配置文件:

?

1

2

3

4

5

6

<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl">

  <property name="userDao" ref="userDao" />

</bean>

<bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl"> 

  <property name="sessionFactory" ref="mySessionFactory" />

</bean>

1.2. 引入@Autowired注解(不推荐使用,建议使用@Resource) 
类的实现(对成员变量进行标注)

?

1

2

3

4

5

publicclass  UserManagerImpl implementsUserManager {

  @Autowired

  privateUserDao userDao;

  ...

}

或者(对方法进行标注)

?

1

2

3

4

5

6

7

8

UserManagerImpl implementsUserManager {

  privateUserDao userDao;

  @Autowired

  publicvoid  setUserDao(UserDao userDao) {

    this.userDao = userDao;

  }

  ...

}

配置文件

?

1

2

3

4

<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl" />

<bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl"> 

  <property name="sessionFactory" ref="mySessionFactory" />

</bean>

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

1.3. 让@Autowired工作起来 
要使@Autowired能够工作,还需要在配置文件中加入以下代码

?

1

class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

1.4. @Qualifier 
@Autowired是根据类型进行自动装配的。在上面的例子中,如果当Spring上下文中存在不止一个UserDao类型的bean时,就会抛出BeanCreationException异常;如果Spring上下文中不存在UserDao类型的bean,也会抛出BeanCreationException异常。我们可以使用@Qualifier配合@Autowired来解决这些问题。 
1. 可能存在多个UserDao实例

?

1

2

3

4

@Autowired

publicvoid  setUserDao(@Qualifier("userDao") UserDao userDao) {

  this.userDao = userDao;

}

这样,Spring会找到id为userDao的bean进行装配。 
2. 可能不存在UserDao实例

?

1

2

3

4

@Autowired(required = false)

publicvoid  setUserDao(UserDao userDao) {

  this.userDao = userDao;

}

1.5. @Resource(JSR-250标准注解,推荐使用它来代替Spring专有的@Autowired注解) 
Spring 不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource、@PostConstruct以及@PreDestroy。 
@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按byName自动注入罢了。@Resource有两个属性是比较重要的,分别是name和type,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)进行匹配,如果匹配则自动装配;
1.6. @PostConstruct(JSR-250) 
在方法上加上注解@PostConstruct,这个方法就会在Bean初始化之后被Spring容器执行(注:Bean初始化包括,实例化Bean,并装配Bean的属性(依赖注入))。 
它的一个典型的应用场景是,当你需要往Bean里注入一个其父类中定义的属性,而你又无法复写父类的属性或属性的setter方法时,如: 

?

1

2

3

4

5

6

7

8

9

10

11

12

publicclass  UserDaoImpl extendsHibernateDaoSupport implementsUserDao {

  privateSessionFactory mySessionFacotry;

  @Resource

  publicvoid  setMySessionFacotry(SessionFactory sessionFacotry) {

    this.mySessionFacotry = sessionFacotry;

  }

  @PostConstruct

  publicvoid  injectSessionFactory() {

    super.setSessionFactory(mySessionFacotry);

  }

  ...

}

这里通过@PostConstruct,为UserDaoImpl的父类里定义的一个sessionFactory私有属性,注入了我们自己定义的sessionFactory(父类的setSessionFactory方法为final,不可复写),之后我们就可以通过调用super.getSessionFactory()来访问该属性了。


1.7. @PreDestroy(JSR-250) 
在方法上加上注解@PreDestroy,这个方法就会在Bean初始化之后被Spring容器执行。由于我们当前还没有需要用到它的场景,这里不不去演示。其用法同@PostConstruct。

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

?

1

2

3

4

5

6

7

<beansxmlns="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/>

</beans>

<context:annotationconfig />将隐式地向Spring容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、 PersistenceAnnotationBeanPostProcessor以及RequiredAnnotationBeanPostProcessor这4个BeanPostProcessor。

2. 使用Spring注解完成Bean的定义 
以上我们介绍了通过@Autowired或@Resource来实现在Bean中自动注入的功能,下面我们将介绍如何注解Bean,从而从XML配置文件中完全移除Bean定义的配置。

2.1. @Component(不推荐使用)、@Repository、@Service、@Controller 
只需要在对应的类上加上一个@Component注解,就将该类定义为一个Bean了:

?

1

2

3

4

@Component

publicclass  UserDaoImpl extendsHibernateDaoSupport implementsUserDao {

  ...

}

使用@Component注解定义的Bean,默认的名称(id)是小写开头的非限定类名。如这里定义的Bean名称就是userDaoImpl。你也可以指定Bean的名称: 
@Component("userDao") 
@Component是所有受Spring管理组件的通用形式,Spring还提供了更加细化的注解形式:@Repository、@Service、@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。目前版本(2.5)中,这些注解与@Component的语义是一样的,完全通用,在Spring以后的版本中可能会给它们追加更多的语义。所以,我们推荐使用@Repository、@Service、@Controller来替代@Component。

2.2. 使用<context:component-scan />让Bean定义注解工作起来

?

1

2

3

4

5

6

7

<beansxmlns="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-scanbase-package="com.kedacom.ksoa"/>

</beans>

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

过滤器类型 表达式范例 说明
注解 org.example.SomeAnnotation 将所有使用SomeAnnotation注解的类过滤出来
类名指定 org.example.SomeClass 过滤指定的类
正则表达式 com\.kedacom\.spring\.annotation\.web\..* 通过正则表达式过滤一些类
AspectJ表达式 org.example..*Service+ 通过AspectJ表达式过滤一些类

以正则表达式为例,我列举一个应用实例:

?

1

2

3

<context:component-scanbase-package="com.casheen.spring.annotation">

  <context:exclude-filtertype="regex"expression="com\.casheen\.spring\.annotation\.web\..*"/>

</context:component-scan>

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

2.3. 使用@Scope来定义Bean的作用范围 
在使用XML定义Bean时,我们可能还需要通过bean的scope属性来定义一个Bean的作用范围,我们同样可以通过@Scope注解来完成这项工作:

?

1

2

3

4

5

@Scope("session")

@Component()

publicclass  UserSessionBean implementsSerializable {

  ...

}

3.在使用annotation之前定义三个bean之间的关系是这样的

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

packagecom.baobaotao;

publicclass  Office {

  privateString officeNo =”001”;

  

  //省略 get/setter

  

  @Override

  publicString toString() {

    return"officeNo:"  + officeNo;

  }

}

 

ackage com.baobaotao;

  

publicclass  Car {

  privateString brand;

  privatedouble  price;

  

  // 省略 get/setter

  

  @Override

  publicString toString() {

    return"brand:"  + brand + ",""price:"+ price;

  }

}

 

packagecom.baobaotao;

  

publicclass  Boss {

  privateCar car;

  privateOffice office;

  

  // 省略 get/setter

  

  @Override

  publicString toString() {

    return"car:"  + car + "\n""office:"+ office;

  }

}

配置文件如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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">

  <beanid="boss"class="com.baobaotao.Boss">

    <propertyname="car"ref="car"/>

    <propertyname="office"ref="office"/>

  </bean>

  <beanid="office"class="com.baobaotao.Office">

    <propertyname="officeNo"value="002"/>

  </bean>

  <beanid="car"class="com.baobaotao.Car"scope="singleton">

    <propertyname="brand"value=" 红旗 CA72"/>

    <propertyname="price"value="2000"/>

  </bean>

</beans>

测试文件如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

publicclass  AnnoIoCTest {

  

  publicstatic  void  main(String[] args) {

    String[] locations = {"beans.xml"};

    ApplicationContext ctx =

      newClassPathXmlApplicationContext(locations);

    Boss boss = (Boss) ctx.getBean("boss");

    System.out.println(boss);

  }

}

 
4.接下来我们可以使用autowired来注解,他可以对成员变量,方法及构造函数进行标准,完成自动装配的工作。

autoware来注解成员变量的用法

?

1

2

3

4

5

6

7

8

9

10

11

12

13

packagecom.baobaotao;

importorg.springframework.beans.factory.annotation.Autowired;

  

publicclass  Boss {

  

  @Autowired

  privateCar car;

  

  @Autowired

  privateOffice office;

  

  

}

相应的配置文件如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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 进行自动注入 -->

  <beanclass="org.springframework.beans.factory.annotation.

    AutowiredAnnotationBeanPostProcessor"/>

  

  <!-- 移除 boss Bean 的属性注入配置的信息 -->

  <beanid="boss"class="com.baobaotao.Boss"/>

  

  <beanid="office"class="com.baobaotao.Office">

    <propertyname="officeNo"value="001"/>

  </bean>

  <beanid="car"class="com.baobaotao.Car"scope="singleton">

    <propertyname="brand"value=" 红旗 CA72"/>

    <propertyname="price"value="2000"/>

  </bean>

</beans>

autoware也可以用在setter方法及构造函数上

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

packagecom.baobaotao;

  

publicclass  Boss {

  privateCar car;

  privateOffice office;

  

   @Autowired

  publicvoid  setCar(Car car) {

    this.car = car;

  }

  

  @Autowired

  publicvoid  setOffice(Office office) {

    this.office = office;

  }

  

}

 

packagecom.baobaotao;

  

publicclass  Boss {

  privateCar car;

  privateOffice office;

  

  @Autowired

  publicBoss(Car car ,Office office){

    this.car = car;

    this.office = office ;

  }

  

  

}

当候选bean的数目为0时,我们可以使用@Autowired(required = false)来防止spring找不到bean时报错。

当有多个候选bean的时候,我们可以通过@Qualifier 注释指定注入 Bean 的名称。

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

5.@resorce是按照名字来进行反射,他有两个参数,name和type,使用name即按照byname来映射,使用type即按照bytype来进行映射。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

packagecom.baobaotao;

  

importjavax.annotation.Resource;

  

publicclass  Boss {

  // 自动注入类型为 Car 的 Bean

  @Resource

  privateCar car;

  

  // 自动注入 bean 名称为 office 的 Bean

  @Resource(name = "office")

  privateOffice office;

}

@postconstructor和preDestory是用来注解类初始化后和销毁前的方法。

 

 

packagecom.baobaotao;

  

importjavax.annotation.Resource;

importjavax.annotation.PostConstruct;

importjavax.annotation.PreDestroy;

  

publicclass  Boss {

  @Resource

  privateCar car;

  

  @Resource(name = "office")

  privateOffice office;

  

  @PostConstruct

  publicvoid  postConstruct1(){

    System.out.println("postConstruct1");

  }

  

  @PreDestroy

  publicvoid  preDestroy1(){

    System.out.println("preDestroy1");

  }

  

}

6.@compent可以直接定义bean,这样xml配置文件中就不需要配置bean了

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

packagecom.baobaotao;

  

importorg.springframework.stereotype.Component;

  

@Component

publicclass  Car {

  

}

 

packagecom.baobaotao;

  

importorg.springframework.stereotype.Component;

  

@Component

publicclass  Office {

  privateString officeNo = "001";

  

}

 

packagecom.baobaotao;

  

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.beans.factory.annotation.Required;

importorg.springframework.beans.factory.annotation.Qualifier;

importorg.springframework.stereotype.Component;

  

@Component("boss")

publicclass  Boss {

  @Autowired

  privateCar car;

  

  @Autowired

  privateOffice office;

  

}

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

?

1

2

3

4

5

6

7

8

9

10

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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-scanbase-package="com.baobaotao"/>

</beans>

7.@scope可以用来指定其目标

?

1

2

3

4

5

6

packagecom.baobaotao;

importorg.springframework.context.annotation.Scope;

@Scope("prototype")

@Component("boss")

publicclass  Boss {

 

Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository、@Service 和 @Controller。在目前的 Spring 版本中,这 3 个注释和 @Component 是等效的,但是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。虽然目前这 3 个注释和 @Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能。所以,如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用 @Repository、@Service 和 @Controller 对分层中的类进行注释,而用 @Component 对那些比较中立的类进行注释

转载于:http://blog.csdn.net/chenzpandy/article/details/51258012

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值