Spring3.0学习札记一Spring IOC控制反转(2)

16 篇文章 0 订阅
3 篇文章 0 订阅

Bean装配

简化配置方式
    为简化XML文件的配置,越来越多的XML文件采用属性而非子元素配置信息。Spring 2.5开始引入一个新的p命名空间,可以通过<bean>元素属性的方式配置Bean的属性。
<!--采用p命名空间的配置-->
<?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" ?>
<!--声明context命名空间-->
<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">
<!--扫描类包以应用注解定义的Bean-->
<context:componet-scan base-package="com.smart.anno"/>
</beans>
    声明context命名空间后,即可通过context命名空间的componet-scan的base-package属性指定需要扫描的基类包。Spring容器将扫描这个基类包里的所有类,并从类的注解信息中获取Bean的定义信息。
若仅希望扫描特定类,则
<!--Spring仅扫描基类包里anno子包中的类-->
<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  //@Autowred默认按类型匹配的方式
    private LogDao logDao;
    @Autowired(required=false) //如果希望Spring即使找不到匹配的Bean完成注入也不要抛出异常,可使用(required=false)
    @Qualifier("userDao") //如果容器中多个类型为UserDao的Bean,则可通过@Quaifier注解限定所注入Bean的名称
    private UserDao userDao;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值