问题引入:
在使用Spring引入@PropertySource(“classpath:user.properties”)读取配置文件,使用@Value("${user.name}")取配置文件中的值注入到bean类的成员变量中,测试打印toString发现name的值为操作系统当前用户的名字,而使用${user.home}注入的home属性则是当前用户的根目录。
代码:
userBean类:
@Component("userZero")
@PropertySource("classpath:user.properties")
public class User {
@Value("${user.name}")
private String name;
@Value("${user.home}")
private String home;
@Value("1")
private int id;
user.properties:
user.name=jack
user.home=jieshi
测试类:
@Test
public void testUser(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User userZero = (User) context.getBean("userZero");
System.out.println(userZero);
context.close();
}
输出结果:
User{name = Sunset_glow, home = C:\Users\Sunset_glow, id = 1}
Process finished with exit code 0
原因:spring默认会优先加载系统环境变量,此时获取到的username的值实际上指的是当前计算机的用户名。而不是properties配置文件中指定的username的值。
结论:应避免使用user.name和user.home作为properties等文件的值,以免引起冲突