0

I have a use case where i have some classes containing properties and getting initialised at the time of app startup from external source And now i want spring boot auto configured beans like datasource takes properties from these property classes.

example :

@Configuration
public class A {

String url;
String password;
String username:
.
.
.
othere datasource related fields 
.
.
.


getters...
setters...

}

Now this bean will get created at startup and get values from external source. How auto configuration of datasource bean (sql server) can take values from this class and how the initialisation of this bean should be forced before that of datasource.

pvjhs
  • 549
  • 1
  • 9
  • 24

1 Answers1

0

You can use a @ConfigurationProperties annotated class for this. It can be used to read configurations from .properties or from .yml files.

Example of usage:

@Configuration
@PropertySource("classpath:configprops.properties")
@ConfigurationProperties(prefix = "myprop")
public class ConfigProperties {

    private String property1;
    private String property2

    // getters and setters
}

In the .properties file we case store the fields like this:

#My properties
myprop.property1=property
myprop.property2=another property

Now, according to Spring documentation, it is enough to annotate a class with @ConfigurationProperties in order to transform it into a bean and make it be able to be autowired. Usually people tend to apply a @Configuration annotation as well.

Ervin Szilagyi
  • 14,274
  • 2
  • 25
  • 40
  • How beans (like datasource) getting auto configured will know to take properties from the fields of this class. – pvjhs Feb 22 '19 at 19:30
  • You autowire the class inside them. – Ervin Szilagyi Feb 22 '19 at 19:32
  • In that case i have to disable the feature of beans getting autowired (advantage of spring boot) and i have to make the datasource bean myself. – pvjhs Feb 22 '19 at 19:35
  • Dependency injection works if you have Spring present. There are other solutions, like constructor injection to be able to inject dependencies if Spring is not running. – Ervin Szilagyi Feb 22 '19 at 19:37
  • You should not add `@Configuration`. It is used to indicate that a class configures Spring beans and will typically have one or more `@Bean` methods. – Andy Wilkinson Feb 23 '19 at 07:12