慕村8951117
2018-01-19 17:02
gtrfans 可以不使用@ImportResource("classpath:config.xml"),也不必配置xml文件,直接用@PropertySource("classpath:config.properties")就可以获取配置文件的数据。 spring4以上 我用的4.17 为什么 引入无效 输出 uri==>${url} user==>${user} name==>${pass}
https://mp.csdn.net/postedit
参考:https://my.oschina.net/u/2326864/blog/1786955
1。@PropertySource+@Value
要想使用@Value 用${}占位符注入属性,这个bean是必须的(PropertySourcesPlaceholderConfigurer), //这个就是占位bean
如果不用的话,
Value("${url}")
private String url;
@Value("value") 里面的value就是String url的值
加上这段代码,会识别${}占位符:
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
2.@PropertySource+@Value+@Envirment
另一种方式是不用value直接用Envirment变量直接getProperty('key')
@Autowired
private Envirment envirment;
使用envirment.getProperty('key') ;就可以取到属性
我也遇到了这样的问题,暂时不知道为什么,但是用@PropertySource + Environment 却可以正确读到配置
我就是这样的 没问题啊 可是 @Value("${url}") 取不到数据 他去的是${url} 这玩意 跟没识别一样
classpath:一般是在src下面,比如我的src/com/cl/bean/db.properties
我用注解的时候就会classpath:com/cl/bean/db.properties
Spring入门篇
268800 学习 · 1026 问题
相似问题