在使用 spring boot 开发过程中, 经常会定义一些应用自己的属性, 直接写到 application 配置文件中使用 @Value 注解进行使用, 这样使用也没有什么问题. 不过我认为更优雅的方式是定义自己的属性类统一管理, 这样在 idea 中, 既能自动提示, 又能对配置进行分类管理, 显得有条不紊, 下面是具体的配置步骤.
第一步: 添加依赖 (分为 maven 和 gradle 两种方式)
1.1 如果你使用的是 maven
增加依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-configuration-processor</artifactId>
- </dependency>
1.2 如果你使用的是 gradle
增加依赖并且配置 annotationProcessor
- compileOnly 'org.springframework.boot:spring-boot-configuration-processor'
- annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
第二步: 创建配置属性类
- @Data
- @ConfigurationProperties(prefix = "myapp.prefix")
- public class MyAppProperties {
- private String prop1;
- private int prop2;
- }
第三步: 在配置类中增加注解
- @Configuration
- @EnableConfigurationProperties(MyAppProperties.class)
- public class MyConfig {
- }
第四步: 使用属性类
- @Component
- public class MyComponent {
- private final MyAppProperties properties;
- public MyComponent(MyAppProperties properties) {
- this.properties = properties;
- }
- // 现在可以使用了
- }
对了, 别忘记配置你的 application.YAML
- myapp:
- prefix:
- prop1: 1111
- prop2: 2222
或 application.properties
- myapp.prefix.prop1=1111
- myapp.prefix.prop2=2222
另外需要注意: 如果想要 idea 中自动提示生效, 需要重新运行你的应用, 有时候没那么快生效.
来源: http://www.bubuko.com/infodetail-3366228.html