@PropertiesSource註解說明

@PropertySouce是spring3.1開始引入的基於java config的註解

通過@PropertySource註解將properties配置文件中的值存儲到Spring的 Environment中,Environment接口提供方法去讀取配置文件中的值,參數是properties文件中定義的key值。

clearLshjTask.properties文件如下:

jobs.schedule = */5 * * * * ?
package com.chen.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@PropertySource("classpath:config/clearLshjTask.properties")
public class PropertiesConfig {

	@Value("${jobs.schedule}")
	private String corn;
	
	
	
	
	public String getCorn() {
		return corn;
	}




	//要想使用@Value 用${}佔位符注入屬性,這個bean是必須的,這個就是佔位bean,另一種方式是不用value直接用Envirment變量直接getProperty('key')  
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
       return new PropertySourcesPlaceholderConfigurer();
    }
}

我主要解釋一下${jobs.schedule}這個,因爲我已開始接觸@PropertiesSource註解和${}佔位符時繞了很多彎。有的人${}的值沒有注入。你只需要將

//要想使用@Value 用${}佔位符注入屬性,這個bean是必須的,這個就是佔位bean,另一種方式是不用value直接用Envirment變量直接getProperty('key')  
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
       return new PropertySourcesPlaceholderConfigurer();
    }

這個代碼放入其中,你的${}就可以讀取出值了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章