首先我定义了一个properties属性文件,如下。
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/sampledb
userName1=root
userName=testuser
password=1234567
接着我定义了一个类,如下。
@Component
public class MyDataSource {
@Value("${driverClassName}")
private String driverClassName;
@Value("${url}")
private String url;
@Value("${userName}")
private String userName;
@Value("${userName1}")
private String userName1;
@Value("${password}")
private String password;
public String getUserName() {
return userName;
}
public String getUserName1() {
return userName1;
}
public String toString(){
return ToStringBuilder.reflectionToString(this);
}
}
然后定义一个测试类,如下。
public class PlaceholderTest {
private static String[] config = {"com/smart/place/beans.xml"};
public static void main(String[] args) throws SQLException {
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
System.out.println(ctx.getBean(MyDataSource.class));
System.out.println("username: "+ctx.getBean(MyDataSource.class).getUserName()+" username1: "+ctx.getBean(MyDataSource.class).getUserName1());
}
}
接着我定义了一个beans.xml,首先使用传统的PropertyPlaceholderConfigurer配置,如下。
<!--使用传统的PropertyPlaceholderConfigurer-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:com/smart/place/jdbc.properties"
p:fileEncoding="utf-8" />
此时测试的结果为:
com.smart.placeholder.MyDataSource@1e4a7dd4[driverClassName=com.mysql.jdbc.Driver,url=jdbc:mysql://localhost:3306/sampledb,userName=testuser,userName1=root,password=1234567]
username: testuser username1: root
那么问题来了,如果我不使用传统的PropertyPlaceholderConfigurer配置,而使用context:property-placeholder引用属性文件,如下。
<context:property-placeholder
location="classpath:com/smart/place/jdbc.properties" />
此时进行测试得到的结果如下:
com.smart.placeholder.MyDataSource@48a242ce[driverClassName=com.mysql.jdbc.Driver,url=jdbc:mysql://localhost:3306/sampledb,userName=jma7,userName1=root,password=1234567]
username: jma7 username1: root
可以看到username的值不一样,其实jma7是我本地电脑上使用的用户。其中properties里面的其他属性都能够被正常引用,唯独username.
比较困惑,求帮助。