与精通spring boot的磊神交流,他极力推荐spring boot的原因,也是spring改进之处,是不用写大量的xml。
我们知道以前在使用spring的时候,一般都会用注解生成bean,但是有些情况下不得不使用xml配置bean,比如我们经常在application.xml中配置数据库连接源datasource,在xml中指定db数据源url/name/password等。但是用spring boot后,我们可以直接在代码中使用配置文件(application.properties或者application.yaml)的配置
1.在代码中为bean设置配置文件中的值
@Component
public class Test {
@Value("${userNameP}")
private String userName;
}
然后只需要在application.properties定义userNameP=sssss,或者application.yaml中定义userNameP:sssss.注意冒号后面要有一个空格。
一般情况,我们通过别的途径获取参数的时候,都会在代码中设置默认值,防止参数不存在而造成异常。设置默认值的方式如下,只需要在添加":默认值"。
@Component
public class Test {
@Value("${userNameP:xtj332}")
private String userName;
}
默认情况程序会从application.properties或者application.yaml自动查找配置的值,但是我们也可以指定配置文件的所在。如下:
2.ConfigurationProperties
3.配置读取顺序
spring boot读取配置的顺序如下:
1.Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
@TestPropertySource annotations on your tests.
@SpringBootTest#properties annotation attribute on your tests.
Command line arguments.
Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variableor system property)
ServletConfig init parameters.
ServletContext init parameters.
JNDI attributes from java:comp/env.
Java System properties (System.getProperties()).
10.OS environment variables.
11.A RandomValuePropertySource that only has properties in random.*.
12.Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
13.Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
14.Application properties outside of your packaged jar (application.properties and YAMLvariants).
15.Application properties packaged inside your jar (application.properties and YAML variants).
16.@PropertySource annotations on your @Configuration classes.
17.Default properties (specified using SpringApplication.setDefaultProperties).
对我们来说,最容易出错的地方是,虽然我们使用@PropertySource("classpath:mail.properties")指定文件的位置,但是如果application.yaml中有设置值的话,首先会取application.yaml中的值。
4.随机数
spring boot支持在配置文件中使用随机值,支持Long int uuid string等。使用方法很简单,如下:my.secret=${random.value} my.number=${random.int} my.bignumber=${random.long} my.uuid=${random.uuid} my.number.less.than.ten=${random.int(10)} my.number.in.range=${random.int[1024,65536]}
5.在配置文件中使用占位符
app.name=MyApp
app.description=${app.name} is a Spring Boot application
6.使用yaml文件替代Properties
TheYamlPropertiesFactoryBeanwillloadYAMLasPropertiesandtheYamlMapFactoryBeanwillload YAML as a Map.
yaml的不足之处:yaml文件不能通过@PropertySource注解得到,因此如果需要使用@PropertySource注解,需要用peoperties文件。
7.跨域支持
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**");
}
}
}
8.
app.name=MyApp
app.description=${app.name} is a Spring Boot application