关于Spring读取配置文件${user.name}是操作系统当前用户名的现象

编程入门 行业动态 更新时间:2024-10-26 10:27:09

关于Spring读取<a href=https://www.elefans.com/category/jswz/34/1770506.html style=配置文件${user.name}是操作系统当前用户名的现象"/>

关于Spring读取配置文件${user.name}是操作系统当前用户名的现象

问题引入:

在使用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

测试类:

	@Testpublic 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等文件的值,以免引起冲突

更多推荐

关于Spring读取配置文件${user.name}是操作系统当前用户名的现象

本文发布于:2024-03-08 00:24:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1719349.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:配置文件   用户名   操作系统   现象   Spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!