Bean装配
简化配置方式
为简化XML文件的配置,越来越多的XML文件采用属性而非子元素配置信息。Spring 2.5开始引入一个新的p命名空间,可以通过<bean>元素属性的方式配置Bean的属性。
<?xml version="1.0" encoding="UTF-8" ?>
<beans xlmns="http://www.springframework.org/schema/beans"
.....
xlmns:p="http://www.springframework.org/schema/p"
>
<bean id="car" class="com.smart.ditype.Car"
p:brand="红旗"
p:maxSpeed="200"
p:price="20000.00"/>
<bean id="boss" class="com.smart.ditype.Boss"
p:car-ref="car"/>
</beans>
基于注解的配置
使用注解定义Bean
如果使用基于XML的配置,Bean定义信息和Bean实现类本身是分离的,而采用基于注解的配置方式,Bean定义信息通过在Bean实现类上标注注解实现。
package com.smart.anno
import org.framework.stereotype.Component;
@Component("userDao")
public class UserDao{
...
}
使用@Componet注解在UserDao类声明处对类进行标注,它可以被Spring容器识别,Spring容器自动将POJO转换为容器管理的Bean.
它和以下的XML配置是等效的。
<bean id="userDao" class="com.smart.anno.UserDao">
除了@componet外,Spring还提供了以下三种Bean的注解:
- @Repository: 用于对DAO实现类进行标注
- @Service: 用于对Service实现类进行标注
- @Controller:用于对Controller实现类进行标注
使用注解配置信息启动Spring容器
Spring2.5后提供了一context命名空间,它提供了通过扫描类包以应用注解定义Bean的方式。
<?xml version="1.0" encoding="UTF-8" ?>
<beans xlmns="http://www.springframework.org/schema/beans"
.....
xlmns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:componet-scan base-package="com.smart.anno"/>
</beans>
声明context命名空间后,即可通过context命名空间的componet-scan的base-package属性指定需要扫描的基类包。Spring容器将扫描这个基类包里的所有类,并从类的注解信息中获取Bean的定义信息。
若仅希望扫描特定类,则
<context:componet-scan base-package="com.smart.anno" resouce-pattern="anno/*.class"/>
若需过滤某些子元素,则
<context:componet-scan base-package="com.smart">
<context:include-filter type="regex" expression="com.smart.anno.*"/>
<context:exclude-filter type="aspectj" expression="com.smart..*Controller+"/>
</context:componet-scan>
< context:include-filter >表示要包含的目标类,< context:exclude-filter >表示要排除在外的目标类。
自动装备Bean
Spring通过@Autowired注解实现Bean的依赖注入
package com.smart.anno
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public Class LoginService{
@Autowired
private LogDao logDao;
@Autowired(required=false)
@Qualifier("userDao")
private UserDao userDao;
}