java 在 `@Bean` 方法上使用 `@ConfigurationProperties` 注释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43232021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using `@ConfigurationProperties` annotation on `@Bean` Method
提问by tmj
Could someone give a MWE of how to use the @ConfigurationProperties
annotation directly on a @Bean
method?
有人可以提供有关如何@ConfigurationProperties
直接在@Bean
方法上使用注释的 MWE吗?
I have seen countless examples of it being used on class definitions - but no examples yet for @Bean
methods.
我已经看到无数将它用于类定义的示例 - 但还没有用于@Bean
方法的示例。
To quote the documentation:
引用文档:
- Add this to a class definition or a
@Bean
method - @Target(value={TYPE,METHOD})
- 这种添加到一个类定义或一个
@Bean
方法 - @目标(值={类型,方法})
So, I think there is a possibility and an intended use as well - but unluckily I am unable to figure it out.
所以,我认为也有一种可能性和预期用途 - 但不幸的是我无法弄清楚。
回答by Evgeni Dimitrov
spring.datasource.url = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
spring.datasource.driverClassName = oracle.jdbc.OracleDriver
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return new DataSource();
}
Here the DataSource class has proeprties url, username, password, driverClassName, so spring boot maps them to the created object.
这里DataSource类有属性url、用户名、密码、driverClassName,所以spring boot将它们映射到创建的对象上。
Example of the DataSource class:
DataSource 类的示例:
public class DataSource {
private String url;
private String driverClassName;
private String username;
private String password;
//getters & setters, etc.
}
In other words this has the same effect as if you initialize some bean with stereotype annotations(@Component, @Service, etc.) e.g.
换句话说,这与使用构造型注释(@Component、@Service 等)初始化某个 bean 的效果相同,例如
@Component
@ConfigurationProperties(prefix="spring.datasource")
public class DataSource {
private String url;
private String driverClassName;
private String username;
private String password;
//getters & setters, etc.
}
回答by Michael Ushakov
I found following solution: i.e. we have in application yaml couple of section and we are interesting in appConfig:
我找到了以下解决方案:即我们在应用程序 yaml 中有几个部分,我们在 appConfig 中很有趣:
appConfig:
version: 1.0_alpha
environment: ${spring.profiles}
dbDriver: ${spring.datasource.driver-class-name}
dbUrl: ${spring.datasource.url}
keyCloak:
serverOne:
host: http://xx.xx.xxx.xxx:8080
baseUrl: ${appConfig.keyCloak.serverOne.host}/auth/realms/master
clientId: api-service-agent
clientSecret: f00955443-d123-4cfe-90d3-e3ff3b214aaffe
serviceUsername: service-user
servicePassword: 1234567890
serverTwo:
host: http://xx.xxx.xxx.xxx:8080
baseUrl: ${appConfig.keyCloak.serverTwo.host}/auth/realms/wissance
clientId: api-service-agent
clientSecret: a20ddf0-56fa-4991-85bc-114377eeffddcc
serviceUsername: service-user
servicePassword: 1234567890
using:
baseUrl: ${appConfig.keyCloak.serverTwo.baseUrl}
clientId: ${appConfig.keyCloak.serverTwo.clientId}
clientSecret: ${appConfig.keyCloak.serverTwo.clientSecret}
serviceUsername: ${appConfig.keyCloak.serverTwo.serviceUsername}
servicePassword: ${appConfig.keyCloak.serverTwo.servicePassword}
We would like to split common settings and using KeyCloak settings, so i implemented following scheme:
我们想拆分通用设置并使用 KeyCloak 设置,所以我实现了以下方案:
I make following KeyCloakConfig class (without @ConfigurationProperties annotation) to store using authentication server settings:
我制作了以下 KeyCloakConfig 类(没有 @ConfigurationProperties 注释)来使用身份验证服务器设置进行存储:
@Configuration
public class KeyCloakConfig {
public KeyCloakConfig(){
}
public KeyCloakConfig(String baseUrl, String clientId, String clientSecret, String username, String password) {
this.baseUrl = baseUrl;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.username = username;
this.password = password;
}
public String getBaseUrl(){
return baseUrl;
}
public void setBaseUrl(String baseUrl){
this.baseUrl = baseUrl;
}
public String getClientId(){
return clientId;
}
public void setClientId(String clientId){
this.clientId = clientId;
}
public String getClientSecret(){
return clientSecret;
}
public void setClientSecret(String clientSecret){
this.clientSecret = clientSecret;
}
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
@Value("${appConfig.keyCloak.using.baseUrl}")
private String baseUrl;
@Value("${appConfig.keyCloak.using.clientId}")
private String clientId;
@Value("${appConfig.keyCloak.using.clientSecret}")
private String clientSecret;
@Value("${appConfig.keyCloak.using.serviceUsername}")
private String username;
@Value("${appConfig.keyCloak.using.servicePassword}")
private String password;
}
and AppConfig class that holds common settings like version, environment using DB driver & url and also KeyCloakConfig as property:
和 AppConfig 类,它包含常用设置,如版本、使用 DB 驱动程序和 url 的环境以及 KeyCloakConfig 作为属性:
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class AppConfig {
public AppConfig(){
}
public AppConfig(String apiVersion, String environment, String databaseDriver, String databaseUrl){
this.apiVersion = apiVersion;
this.environment = environment;
this.databaseDriver = databaseDriver;
this.databaseUrl = databaseUrl;
}
public String getEnvironment(){
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
public String getDatabaseDriver(){
return databaseDriver;
}
public void setDatabaseDriver(String databaseDriver) {
this.databaseDriver = databaseDriver;
}
public String getDatabaseUrl(){
return databaseUrl;
}
public void setDatabaseUrl(String databaseUrl) {
this.databaseUrl = databaseUrl;
}
public String getApiVersion(){
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public KeyCloakConfig getKeyCloakConfig(){
return keyCloakConfig;
}
public void setKeyCloakConfig(KeyCloakConfig keyCloakConfig){
this.keyCloakConfig = keyCloakConfig;
}
@Value("${appConfig.version}")
private String apiVersion;
@Value("${appConfig.environment}")
private String environment;
@Value("${appConfig.dbDriver}")
private String databaseDriver;
@Value("${appConfig.dbUrl}")
private String databaseUrl;
@Autowired
private KeyCloakConfig keyCloakConfig;
}
回答by u6856342
24.8.1 Third-party Configuration
As well as using @ConfigurationProperties
to annotate a class, you can also use it on public @Bean
methods. Doing so can be particularly useful when you want to bind properties to third-party components that are outside of your control.
除了@ConfigurationProperties
用于注释类之外,您还可以在公共@Bean
方法上使用它。当您想要将属性绑定到您无法控制的第三方组件时,这样做会特别有用。
To configure a bean from the Environment properties, add @ConfigurationProperties
to its bean registration, as shown in the following example:
要从 Environment 属性配置 bean,请添加@ConfigurationProperties
到其 bean 注册中,如以下示例所示:
@ConfigurationProperties(prefix = "another")
@Bean
public AnotherComponent anotherComponent() {
...
}
Any property defined with the another prefix is mapped onto that AnotherComponent bean in manner similar to the preceding AcmeProperties example.
使用 another 前缀定义的任何属性都以类似于前面的 AcmeProperties 示例的方式映射到该 AnotherComponent bean。
回答by KevinBui
You can use @ConfigurationProperties as below
您可以使用@ConfigurationProperties 如下
Entity Model
实体模型
public class MY_ENTITY {
private String prop1;
private String prop2;
// setter & getter & toString()
}
Bean Method
豆方法
@Configuration
public class MyClass {
@Bean
@ConfigurationProperties(prefix = "my.entity")
public MY_ENTITY getContract() {
return new MY_ENTITY()
.setProp1("prop1111111")
.setProp2("prop2222222")
;
}
@Bean(name = "contract2")
@ConfigurationProperties(prefix = "my.entity2")
public MY_ENTITY getContract2() {
return new MY_ENTITY()
.setProp1("prop1111.2222")
.setProp2("prop2222.222")
;
}
}
application.properties
应用程序属性
my.entity.prop1=2120180023
my.entity.prop2=CUSTOMER_NAME111
my.entity2.prop1=9994494949
my.entity2.prop2=CUSTOMER_NAME222
SpringBootApplication
SpringBoot应用程序
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Autowired
@Qualifier("contract2")
private MY_ENTITY myEntity;
public static void main(String[] args) throws Exception {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println(myEntity);
}
}