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

这个代码放入其中,你的${}就可以读取出值了。

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