使用注解类:
需要在配置中添加context命名空间:如下
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=".. http://www.springframework.org/schema/context
http://springframework.org/schema/context/spring-context-3.0.xsd.."
使用:
<context:component-scan base-package="包路径" >
<context:include-fileter type="类型" expression="匹配" /> <!--包含匹配-->
<context:exclude-filter type="类型" expression="匹配路径" /> <!--排除匹配-->
</context:component-scan>
过滤表达式: 详见过滤表达式篇(待添加= =)
基于注解的配置
标示:
@Component("xx")
public class Entity..
等价 <bean id="xx" class="com.bean.Entity" />
类似@Component的有@Repository @Service @Controller 对应mvc3个层次
自动装配:
@Autowired([requied=false|true])
requied属性标示 是否必须有此类型 true如果找不到这个类型则报出异常
@Qualifire("bean id");
指定要注入的类的类名,此注释可以注释在参数上
Bean的作用范围注释:
@Scope("范围名");
范围名:prototype singleton request session globalSession
检测属性是否设置:
@Required 设置此注解的属性必须初始化
生命周期
@PostConstruct
载入配置文件时运行
@PreDestory
关闭到时候运行
基于Java类的配置
@Configuration
在类上标注,为Spring容器提供Bean定义的信息
@bean
给方法标注,此方法提供Bean的实例化
Spring会对标注@bean的方法进行AOP改造,使之进行AOP注入操作
例如:
@Configuration
public class A {
@Bean
public B getB(){
return new B();
}
public Login logonService(){
Login login=new Login();
login.setB(getB());
}
}
等同xml配置:
<bean id="a" class="xxxx.A" />
<bean id="logon" class="xxxx.Login" p:getB-ref="a" />
即A类提供对login类中的方法进行依赖注入
@Configruation有@Component注解的含义
即@Configruation会被context:component-scan所自动扫描入容器
基于注解的java属性配置
需要在配置文件中加入,导入的properties文件
<context:propterty-placeholder location="properties的位置" />
然后再类属性加入注解
@Value("${properties的key名}")
引用类的属性:
@Value("#{beanName.property}")