当我们使用spring的setter对bean的引用对象注入时会这样用
<bean id="testBean" class="TestBean">
<property name="hello1" value="${hello}"></property>
<property name="hello2" value="hello & world!"></property>
</bean>
但是你知道引用properties文件的设置和直接设置的区别吗
区别在于:
引用properties文件中key所对应的value时 spring不会做任何处理直接注入值
直接注入时spring会作转义处理
我们来看下以下示例:
创建一个bean,有hello1和hello2两个属性 通过setter注入
public class TestBean {
private String hello1;
private String hello2;
public String getHello1() {
return hello1;
}
public void setHello1(String hello1) {
this.hello1 = hello1;
}
public String getHello2() {
return hello2;
}
public void setHello2(String hello2) {
this.hello2 = hello2;
}
}
xml中配置bean ,hello1引用config.properties文件中key为hello的值
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<context:property-placeholder location="classpath:test-config.properties" />
<bean id="testBean" class="TestBean">
<property name="hello1" value="${hello}"></property>
<property name="hello2" value="hello & world!"></property>
</bean>
</beans>
config.properies:
hello = hello & world!
测试类:
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
/**
* @param args
*/
public static void main(String[] args) {
TestBean testBean = (TestBean) new ClassPathXmlApplicationContext("test-spring.xml").getBean("testBean");
System.out.println(testBean.getHello1());
System.out.println(testBean.getHello2());
}
}
输出结果如下:
hello & world!
hello & world!
可以看到同样的值输出了不同的结果 证实我们开头所说:
引用properties文件中key所对应的value时 spring不会做任何处理直接注入值
直接注入时spring会作转义处理