详解Spring Boot加载properties和yml配置文件
一、系统启动后注入配置
packagecom.example.config;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.PropertySource;
importorg.springframework.core.env.Environment;
/**
*@author:GrandKai
*@create:2016-09-0111:24
*/
@Configuration
@PropertySource(ignoreResourceNotFound=true,value={"classpath:/config/email.properties","classpath:/config/email.yml"},name="email")
publicclassConfig{}
需要在ApplicationContext中注册配置
AnnotationConfigEmbeddedWebApplicationContextcontext=(AnnotationConfigEmbeddedWebApplicationContext)app.run("参数1");
context.register(Config.class);
用以下方式取值
Environmentenv=context.getEnvironment();
System.out.println(env.getProperty("address"));
email.yml文件配置如下:
server: address:127.0.0.1
二、在命令行传入注入到程序中
publicclassMain{
publicstaticvoidmain(String...args){
//initializethecommandlineparsingstuff
OptionParserparser=newOptionParser();
parser.accepts("greeting").withRequiredArg();
OptionSetoptions=parser.parse(args);
//createtheactualSpringPropertySource
PropertySource>ps=newJOptCommandLinePropertySource(options);
//setuptheSpringcontext
AnnotationConfigApplicationContextctx=newAnnotationConfigApplicationContext();
ctx.getEnvironment().getPropertySources().addLast(ps);
//registerthepropertysourcewiththeenvironment
ctx.register(Greeter.class);
ctx.refresh();
Greetergreeter=ctx.getBean(Greeter.class);
greeter.sayGreeting();
}
}
@Component
classGreeter{
@InjectprivateEnvironmentenv;
//thefollowingwouldalsowork
//@Value("${greeting}")
//privateStringgreeting;
/**
*Printoutthe'greeting'propertyifitexists,andotherwise,"Welcome!".
*/
publicvoidsayGreeting(){
System.out.println(env.getProperty("greeting","Welcome!"));
}
}
publicstaticvoidmain(String[]args){
SimpleCommandLinePropertySourceps=newSimpleCommandLinePropertySource(args);
@SuppressWarnings("resource")
AnnotationConfigApplicationContextctx=newAnnotationConfigApplicationContext();
ctx.getEnvironment().getPropertySources().addFirst(ps);
ctx.register(ApplicationConfig.class);
ctx.refresh();
}
@Configuration
@EnableScheduling
@ComponentScan("com.mycompany.package")
@PropertySource(
value={"classpath:/application.properties","file:${config.location}"},
ignoreResourceNotFound=true
)
classApplicationConfig{
@Bean
publicstaticPropertySourcesPlaceholderConfigurerpropertyConfigurer(){
returnnewPropertySourcesPlaceholderConfigurer();
}
}
@Component
classMyComponent{
@Value("${my.property.data}")
privateStringmyPropertyData;
@Scheduled(fixedDelayString="${schedule.delay.period}")
publicvoidrun(){
:
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。