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:
@Bean
method So, I think there is a possibility and an intended use as well - but unluckily I am unable to figure it out.
@ConfigurationProperties allows to map the entire Properties and Yaml files into an object easily. It also allows to validate properties with JSR-303 bean validation. By default, the annotation reads from the application.
@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .
We can also declare beans using the @Bean annotation in a configuration class. Finally, we can mark the class with one of the annotations from the org. springframework.
The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.
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. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With