springboot中通常在application.properties文件中设置属性。也可以通过SpringApplication的setDefaultProperties方法设置属性,如下:
pom.xml
4.0.0
com.edu.spring
springboot
1.0.0
jar
springboot
http://www.example.com
org.springframework.boot
spring-boot-dependencies
2.1.6.RELEASE
import
pom
UTF-8
1.8
1.8
org.springframework.boot
spring-boot-starter
View Code
App.java
packagecom.edu.spring.springboot;importjava.util.HashMap;importjava.util.Map;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.SpringApplication;importorg.springframework.context.ConfigurableApplicationContext;public classApp
{
@Value("${server.host:localhost}")privateString serverhost;public static voidmain( String[] args)
{
SpringApplication app=new SpringApplication(App.class);
Map map=new HashMap<>();
map.put("server.host","127.0.0.1");
app.setDefaultProperties(map);
ConfigurableApplicationContext context=app.run(args);
System.out.println(context.getBean(App.class).serverhost);
context.close();
}
}
View Code
运行结果如下:
如果在application.properties文件中设置相同的属性,最终获取的是配置文件中的属性,如下:
application.properties
server.host=192.168.1.100
View Code
运行结果如下: