天天看點

@Value和@PropertySource讀配置檔案采坑留念

一、 網上查到的方式:

直接 @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);
	}
}
           

總結:

  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屬性

繼續閱讀