在@Bean方法上使用@ConfigurationProperties批注 [英] Using `@ConfigurationProperties` annotation on `@Bean` Method

查看:1186
本文介绍了在@Bean方法上使用@ConfigurationProperties批注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆