SpringBoot
配置文件内容获取
前提
- 添加以下依赖
1 | <dependency> |
新建实体类获取application.yml/applicaiton.properties
配置文件内容
@Component
、@ConfigurationProperties
注解
application.yml
配置文件
1 | server: |
实体类
1 | import org.springframework.boot.context.properties.ConfigurationProperties; |
测试类
- 测试是否能够正确获取配置文件内容
1 | (SpringRunner.class) |
@Component
、@Value
注解
application.yml/application.properties
文件内容不变
实体类
1 | import org.springframework.boot.context.properties.ConfigurationProperties; |
测试类
1 | (SpringRunner.class) |
创建实体类获取自定义(xx.properties
)配置文件内容
- 注: 自定义配置文件最好还是使用
.properties
格式的文件,注解方式还不支持手动加载.yml
格式文件的功能
@Configuration
注解替换@Component
注解,@PropertySource("classpath:xx.properties")
创建自定义配置文件
my.properties
1 | # 高德——地理编码 |
实体类
1 |
|
测试类
1 | (SpringRunner.class) |
- 配置文件可创建在
resource
中的文件夹下,使用相对根目录的文件夹即可(默认resources/
为根目录)
@Configuration
、@PropertySource
、@ConfigurationProperties
- 注: 使用
@configuration
与@ConfigurationProperties
注解时,需要在启动类(Application.java
)中增加@EnableConfigurationProperties(PhoneProperties.class)
注解。
配置文件
- 配置文件路径
resources/properties/phone.properties")
1 | phone.model= iPhone 8 Plus |
启动类
1 |
|
配置文件实体类
1 |
|
测试类
1 | (SpringRunner.class) |
使用Environment
方法获取配置文件的值
注解说明
@Component
将普通的
pojo
实例化到Spring
容器中,相当于xml
配置文件中的<bean id="" class=""/>
;泛指组件,当组件不好归类的的时候,可以使用这个组件。
@Configutration
用于定义配置类;
@Configuration
中所有带@Bean
注解的方法都会被动态代理,因此调用该方法返回的都是同一个实例。@Component
与@Component
区别详细介绍,Spring @Configuration 和 @Component
区别
@PropertySource
- 通过注解的方式将
properties
配置文件中的值存储到Spring
的Enviroment
中,Environment
接口提供方法去读取配置文件中的值,参数时properties
文件中定义的key
值。
- 通过注解的方式将
@ConfigurationProperties
将同类的配置信息封装成实体类;
与
@ConfigurationProperties
一起使用时,需要在启动类增加@EnableConfigurationProperties
注解并制定该实体类为配置类 或 使用@Component
注解替代@Configuration
注解。
@Value
@value
属性名,在属性名上添加该注解;默认读取的配置文件是
application.yml/application.properties
,可在@RestController/@Controller
中获取配置。
常见问题
在非Controller
中无法获取配置类 或 注入相应注解
Controller
中无法获取配置类 或 注入相应注解- 在工具类中,获取
RestTemplate
注解以及自定义配置文件为例
1 | // Point 1: 使用类注解`@Conponent` |
注解说明
@PostConstruct
- 被
@PostConstruct
修饰的方法会在服务器加载Servlet
的时候运行,并且只会被服务器调用一次,类似于Servlet
的init()
方法。被@PostContruct
修饰的方法会在构造函数之后,init()
方法之前运行。 @PostContruct
注释的init()
方法,会在@Configuration
配置之前运行。例如: 在执行预加载函数前,需要加载配置项则需要implements CommandLineRunner
接口,若使用@PostContruct
则只有在init()
方法执行完才能获取@Configuration
注解的自定义配置项。
- 被