@PropertySource 無法讀取配置文件的屬性值解決方案
原來Person類這樣寫: 只寫了@PropertySource注解
@Component
@PropertySource(value = {"classpath:person.properties"})
public class Person {
private String lastName;
private int age;
private boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
...
}
運行后找不到配置文件中的值:

解決方法:
加上@ConfigurationProperties注解:
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})
public class Person {
運行,獲取到配置文件中的值:

為啥呢??
因為 @ConfigurationProperties(prefix = “person”)表示該類的屬性值為配置中的屬性值,找前綴為person的屬性。
首先從全局配置文件中找是否有person對應的屬性值,如果有那么就輸出全局配置中的屬性值;如果沒有,@PropertySource意思是屬性來源,從@PropertySource指定的路徑中找到對應的配置文件,進行賦值。
@Value和@PropertySource讀配置文件采坑留念
一、 網上查到的方式:
直接 @PropertySource加載文件@Value讀取屬性,
Environment.getProperty()獲取屬性。
結果發(fā)現@Value只能拿到"${ips}",獲取不到配置文件里的屬性。
@Controller
@PropertySource("classpath:queryScoreIPList.properties")
public class UserController {
@Value("${ips}")
private String ips;
@Autowired
private Environment environment;
public void user() {
System.err.println(ips);
System.err.println(environment.getProperty("ips"));
}
}
二、 其他方式:
兩種方式加載配置文件,
@Value正常獲取屬性,
Environment.getProperty()獲取不到屬性。
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:queryScoreIPList.properties</value>
</list>
</property>
</bean>
<context:property-placeholder ignore-unresolvable="true" location="classpath:queryScoreIPList.properties" />
三、非要@PropertySource+@Value也可以:
spring配置里裝配PropertySourcesPlaceholderConfigurer或配置context:property-placeholder,
代碼里@PropertySource加載配置文件,
@Value獲取屬性,Environment.getProperty()正常獲取屬性。
<!-- <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"/> --> <context:property-placeholder/>
@Controller
@PropertySource("classpath:queryScoreIPList.properties")
public class UserController {
@Value("${ips}")
private String ips;
public void user() {
System.err.println(ips);
}
}
總結:
1、@Value從PropertySourcesPlaceholderConfigurer類的PropertySources集合中獲取屬性。
2、PropertySourcesPlaceholderConfigurer初始化時會將Environment作為PropertySource放到集合中。
3、@PropertySource注解只加載配置文件到Environment。
4、啟動時@PropertySource注解初始化早于PropertySourcesPlaceholderConfigurer(與@PropertySource所在類和PropertySourcesPlaceholderConfigurer裝配順序無關),并且@PropertySource加載的配置在xml文件中可以正常獲取。
com.controller.user.UserController.java
@Controller
@PropertySource(value="classpath:propList.properties")
public class UserController {
@Value("${ips}")
private String ips;
public void user() {
System.err.println(ips);
System.err.println(environment.getProperty("ips"));
}
}
applicationContext.xml
<context:component-scan base-package="com.dao"/>
<context:component-scan base-package="com.controller"/>
<context:property-placeholder location="${location}"/>
propList.properties
location:classpath:queryScoreIPList.properties
以上代碼可以正常獲取queryScoreIPList.properties文件中的ips屬性。希望能給大家一個參考,也希望大家多多支持腳本之家。

