Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

java - Using `@ConfigurationProperties` annotation on `@Bean` Method

Could someone give a MWE of how to use the @ConfigurationProperties annotation directly on a @Bean method?

I have seen countless examples of it being used on class definitions - but no examples yet for @Bean methods.

To quote the documentation:

  • 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.

Example of the DataSource class:

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
@ConfigurationProperties(prefix="spring.datasource")
public class DataSource {
    private String url;
    private String driverClassName;
    private String username;
    private String password;
    //getters & setters, etc.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...