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

前端 未结 4 1773
栀梦
栀梦 2020-12-14 16:38

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

I have seen countless examples o

4条回答
  •  情书的邮戳
    2020-12-14 17:04

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

提交回复
热议问题