【发布时间】:2017-01-04 07:53:45
【问题描述】:
我使用 IntellijIdea 和 gradle。 Gradle 配置:
...
apply plugin: 'propdeps'
apply plugin: 'propdeps-idea'
apply plugin: 'propdeps-maven'
buildscript {
repositories {
maven { url 'http://repo.spring.io/plugins-release' }
}
dependencies {
classpath 'org.springframework.build.gradle:propdeps-plugin:0.0.7'
}
}
compileJava.dependsOn(processResources)
dependencies {
...
optional group: 'org.springframework.boot', name: 'spring-boot-configuration-processor', version: '1.4.0.RELEASE'
}
好的,我需要创建自己的属性:
@Component
@ConfigurationProperties("own.prefix")
@Data
public class TestProps {
public String field;
}
@Configuration
@EnableConfigurationProperties(TestProps.class)
public class AppConf {}
在我重建项目 spring-boot-configuration-processor 后生成新的 META-INFO,所以在 application.properties 中我可以使用 own.prefix.field= 和 Spring 看到它。
但是我应该如何处理 3rd 方配置类? 文档http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html 说:
除了使用
@ConfigurationProperties来注释一个类,你 也可以在@Bean方法上使用它。这可能特别有用 当您想将属性绑定到第三方组件时 不在你的控制范围内。要从环境属性配置 bean,请添加
@ConfigurationProperties对其 bean 进行注册:@ConfigurationProperties(prefix = "foo") @Bean public FooComponent fooComponent() { ... }使用 foo 前缀定义的任何属性都将映射到该属性 FooComponent bean 以与 ConnectionProperties 类似的方式 上面的例子。
好的。我们试试吧。例如我在 gide (https://spring.io/guides/tutorials/spring-boot-oauth2/) 中声明 bean:
@Configuration
@EnableOAuth2Sso
public class SocialConfig {
@Bean
@ConfigurationProperties("facebook.client")
OAuth2ProtectedResourceDetails facebook() {
return new AuthorizationCodeResourceDetails();
}
@Bean
@ConfigurationProperties("facebook.resource")
ResourceServerProperties facebookResource() {
return new ResourceServerProperties();
}
}
但重建项目属性 facebook.client 和 facebook.resource 后我的 application.properties 中不存在。
我也尝试将 SocialConfig.class 添加到
@Configuration
@EnableConfigurationProperties(SocialConfig.class)
public class AppConf {}
重建后仍然无法正常工作。 像这样:
@Configuration
@EnableConfigurationProperties
public class AppConf {}
还是一样。
我做错了什么? 也对不起我的英语:)
【问题讨论】:
-
“在我的 application.properties 中不存在”是什么意思?您是说您没有将它们作为自动完成值吗?您不应依赖自动完成值来表示您可以或不能将这些属性添加到配置中。自动完成是减少开发人员对每个属性命名的记忆的最大努力。自动完成功能是您唯一关心的问题,还是您正在尝试解决其他问题并希望自动完成功能成为解决方案?
-
是的,.properties 中的自动完成是问题的主要思想。为什么在第一种情况下它可以正常工作,但在另一种情况下我的 build.gradle 看起来像一个黄色香蕉。我知道我可以隐藏通知,但我想像第一种情况一样实现自动完成。有办法吗?
标签: java spring spring-boot configuration property-files