详解SpringBoot加载properties和yml配置⽂件
⼀、系统启动后注⼊配置
fig;
import org.springframework.beans.factory.annotation.Autowired;
import t.annotation.Configuration;
import t.annotation.PropertySource;
import nv.Environment;
/**
* @author: GrandKai
* @create: 2016-09-01 11:24
*/
@Configuration
@PropertySource(ignoreResourceNotFound = true, value = {"classpath:/config/email.properties","classpath:/l"}, name = "email") public class Config {}
需要在ApplicationContext中注册配置
AnnotationConfigEmbeddedWebApplicationContext context = (AnnotationConfigEmbeddedWebApplicationContext) app.run("参数1"); ister(Config.class);
⽤以下⽅式取值
Environment env = Environment();
System.out.Property("address"));
server:
address: 127.0.0.1
⼆、在命令⾏传⼊注⼊到程序中
public class Main {
public static void args) {
//initialize the command line parsing stuff
OptionParser parser = new OptionParser();
parser.accepts("greeting").withRequiredArg();
OptionSet options = parser.parse(args);
//create the actual Spring PropertySource
PropertySource<?> ps = new JOptCommandLinePropertySource(options);
//setup the Spring context
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
spring怎么读取properties//register the property source with the environment
Greeter greeter = Bean(Greeter.class);
greeter.sayGreeting();
}
}
@Component
class Greeter {
@Inject private Environment env;
//the following would also work
//@Value("${greeting}")
//private String greeting;
/**
* Print out the 'greeting' property if it exists, and otherwise, "Welcome!".
*/
public void sayGreeting() {
System.out.Property("greeting", "Welcome!"));
}
}
public static void main(String [] args) {
SimpleCommandLinePropertySource ps = new SimpleCommandLinePropertySource(args);
@SuppressWarnings("resource")
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
}
@Configuration
@EnableScheduling
@ComponentScan("pany.package")
@PropertySource(
value = {"classpath:/application.properties", "file:${config.location}"},
ignoreResourceNotFound = true
)
class ApplicationConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@Component
class MyComponent {
@Value("${my.property.data}")
private String myPropertyData;
@Scheduled(fixedDelayString = "${schedule.delay.period}")
public void run() {
:
}
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。