IDEA 2021 开发 springboot springcloud springcloud Alibaba应用时application.yml配置自动提示
原创
©著作权归作者所有:来自51CTO博客作者猫头虎技术团队的原创作品,请联系作者获取转载授权,否则将追究法律责任
文章目录

IDEA 2021 开发 springboot springcloud springcloud Alibaba应用时application.yml配置自动提示
方案一:
IDEA开发springboot应用时application.yml配置自动提示
在使用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.yml
myapp:
prefix:
prop1: 1111
prop2: 2222
或 application.properties
myapp.prefix.prop1=1111 myapp.prefix.prop2=2222
另外需要注意:如果想要idea中自动提示生效,需要重新运行你的应用,有时候没那么快生效。
方案二:
安装插件 :spring assistant
1.file—>setting–>plugin 搜索spring assistant安装
确定是否允许annotation processing,打卡 Settings > Build, Execution & Deployment > Compiler > Annotation Processors
Make sure you add the following changes to to your project

For Maven
添加以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
For Gradle
添加
dependencies {
optional "org.springframework.boot:spring-boot-configuration-processor"
}
如果项目里面的application的配置文件后缀为properties改为yml,两种配置文件只是语法有区别,这里因为习惯yaml的写法所以,倾向于使用yml
打开src\main\resources\application.yml,尝试输入,可以看到提示成功
