spring的注解使用和分散配置
一、spring的注解
简介:在 Spring 2.5中已经可以用注解的方式去驱动 Spring 的依赖注射了,@Autowired注解提供了更细致的控制与更好的适应性。Spring 2.5 也支持 JSR-250 中的一些注解,例如@Resource,@PostConstruct,以及@PreDestroy。
a) @Autowired注解配置第一种
Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。@Autowired的标注位置不同,它们都会在Spring在初始化这个bean时,自动装配这个属性。要使@Autowired能够工作,还需要在配置文件中加入以下
<beanclass="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
b) 开启所有的注解
首先加入命名空间和地址,引入context的上下文标签,再使用context:annotation-config标签
该配置可激活在类中探测到的各种注解,@Required @Autowired @PostConstruct @PreDestroy @Resource @EJB @PersistenceContext @WebServiceRef等等,
1 <beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
2 xsi:schemaLocation="http://www.springframework.org/schema/beans
3 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
4 http://www.springframework.org/schema/context
5 http://www.springframework.org/schema/context/spring-context-2.5.xsd">
6 <context:annotation-config/>
7 beans>
二、分散配置
a) 引入外部bean来读取外部配置文件这样在<value>${name}</value>可以使用这个占位符来注入值了
<!--第一种,引入外部bean来读取外部配置文件 -->
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!--引入单个文件-->
<property name="location">
<value>person.properties</value>
</property>
<!--引入多个文件-->
<property name="locations">
<list>
<value>person.properties</value>
</list>
</property>
</bean>
b) 使用spring自带的context工具来读取外部文件
首先需要引入spring的context的命名空间和连接地址 。然后使用
<context:property-placeholderlocation="person.properties"/>来引入文件
c) 定制编辑器后处理类
i. 在配置文件中配置
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<!-- key指向的是:需要转换的类 -->
<entry key="cn.csdn.service.Address">
<!-- value指向的是 实现的编辑器类 -->
<bean class="cn.csdn.editor.AddressEditor"/>
</entry>
</map>
</property>
</bean>
ii. 在java中首先需要继承PropertyEditorSupport这个类然后实现setAsText方法,代码如下
publicclass AddressEditor extends PropertyEditorSupport{
@Override
publicvoid setAsText(String text) throws IllegalArgumentException {
// TODO Auto-generated method stub
//java实现转换
if(!"".equals(text)){
String args[] = text.split("\\.");
if(args.length>3){
Address address = new Address();
address.setProvince(args[0]);
address.setCity(args[1]);
address.setStreet(args[2]);
address.setZipCode(args[3]);
setValue(address);
}else{
this.setAsText(null);
}
}else{
this.setAsText(null);
}
}