在@Bean方法上使用@ConfigurationProperties批注 [英] Using `@ConfigurationProperties` annotation on `@Bean` Method
问题描述
有人可以给MWE直接在@Bean
方法上使用@ConfigurationProperties
注释的方法吗?
Could someone give a MWE of how to use the @ConfigurationProperties
annotation directly on a @Bean
method?
我已经看到了无数示例用于类定义-但是@Bean
方法还没有示例.
I have seen countless examples of it being used on class definitions - but no examples yet for @Bean
methods.
引用文档:
- 将此添加到类定义或
@Bean
方法 - @Target(值= {TYPE,方法})
- Add this to a class definition or a
@Bean
method - @Target(value={TYPE,METHOD})
因此,我认为也有可能,也有预期的用途-但不幸的是,我无法弄清楚.
So, I think there is a possibility and an intended use as well - but unluckily I am unable to figure it out.
推荐答案
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();
}
这里,DataSource类具有属性url,用户名,密码,driverClassName,因此spring boot将它们映射到创建的对象.
Here the DataSource class has proeprties url, username, password, driverClassName, so spring boot maps them to the created object.
DataSource类的示例:
Example of the DataSource class:
public class DataSource {
private String url;
private String driverClassName;
private String username;
private String password;
//getters & setters, etc.
}
换句话说,这与使用构造型注释(@ Component,@ Service等)初始化某些bean的效果相同. 例如
In other words this has the same effect as if you initialize some bean with stereotype annotations(@Component, @Service, etc.) e.g.
@Component
@ConfigurationProperties(prefix="spring.datasource")
public class DataSource {
private String url;
private String driverClassName;
private String username;
private String password;
//getters & setters, etc.
}
这篇关于在@Bean方法上使用@ConfigurationProperties批注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!