一、 网上查到的方式:
直接 @PropertySource加载文件@Value读取属性,
Environment.getProperty()获取属性。
结果发现@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" />
三、非要@[email protected]也可以:
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);
}
}
总结:
- @Value从PropertySourcesPlaceholderConfigurer类的PropertySources集合中获取属性。
- PropertySourcesPlaceholderConfigurer初始化时会将Environment作为PropertySource放到集合中。
- @PropertySource注解只加载配置文件到Environment。
-
启动时@PropertySource注解初始化早于PropertySourcesPlaceholderConfigurer(与@PropertySource所在类和PropertySourcesPlaceholderConfigurer装配顺序无关),并且@PropertySource加载的配置在xml文件中可以正常获取。
com.controller.user.UserController.java
applicationContext.xml@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")); } }
propList.properties<context:component-scan base-package="com.dao"/> <context:component-scan base-package="com.controller"/> <context:property-placeholder location="${location}"/>
以上代码可以正常获取queryScoreIPList.properties文件中的ips属性location:classpath:queryScoreIPList.properties