简述

今天在整合定时任务时,想要把所有的定时任务的执行时间放到配置文件properties文件中,方便管理及修改

    在spring mvc中,在配置文件中的东西,可以在java代码中通过注解进行读取了:
  • @PropertySource 在spring 3.1中开始引入

新建一个jobs.properties 文件

代码中添加 @PropertySource

  • 要注意的是,要使用

      @Bean 
      public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { 
      return new PropertySourcesPlaceholderConfigurer(); 
      }
    

才能让spring正确解析出${} 中的值;

在spring 3.2中,允许支持多个properties了

@Configuration  
    @PropertySource({  
        "classpath:config.properties",  
        "classpath:db.properties" //如果是相同的key,则最后一个起作用  
    })  
    public class AppConfig {  
        @Autowired  
        Environment env;  
    }  

spring 4.1中,支持@PropertySources

@Configuration  
@PropertySources({  
    @PropertySource("classpath:config.properties"),  
    @PropertySource("classpath:db.properties")  
})  
public class AppConfig {  
    //...  
} 

在spring 4.2中,

</pre><pre name="code" class="java">@Configuration  
@PropertySource("classpath:missing.properties")  
public class AppConfig {  
    //...  
}  

如果发现missing.properties不存在,则抛出异常
,也可以使用ignoreResourceNotFound=true去忽略

view plain copy 在CODE上查看代码片派生到我的代码片
    @Configuration   
    @PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)   
    public class AppConfig {   
    //...   
    }