3.2 使用注解装配
从Spring2.5开始,增加了使用注解自动装配Bean属性的新方式,类似于在XML中使用autowire属性自动装配。使用注解方式允许更细粒度的自动装配,可以选择性的标注某一个属性来对其自动装配。
Spring 3 支持三种用于自动装配的注解:
- Spring自带的@Autowired注解
- JSR-330的@Inject注解
- JSR-250的@Resource注解
Spring容器默认禁用注解装配,启用方式:使用Spring的context命名空间配置中的 <context:annotation-config/>元素,告诉Spring开启使用基于注解的自动装配(属性、方法和构造器)。
<?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:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd\
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 要开启注解,首先需要声明context命名空间并引入xsd文件 -->
<!-- 开启注解,告诉Spring我们打算用基于注解的自动装配 -->
<context:annotation-config/>
<bean/>