I'm using Spring Boot and have an external configuration file called application.yml
.
In this file, suppose I have a property foo
that takes a fully-qualified class name as value.
Using Java configuration, what is the typical way to create a bean of the type specified by the foo
property?
I suppose that foo
is implementing some known interface. Otherwise, it is kind of pointless to create a bean of an unknown Type.
Something like:
@Configuration
public class FooConfiguration {
@Value("foo.class-name") // ref to the key used in you application.yml
private String fooClassName;
@Bean
public FooInterface fooBean(){
FooInterface fooImpl = Class.forName(fooClassName).newInstance(); // concreet implemetation
return fooImpl;
}
}
Thank you for this. Wasn't sure if there was some Spring-specific way other than reflection. Yes,
foo
is implementing some known interface.If there is a limited number of known implementations then you could use
@ConditionalOnProperty
and avoid reflection.Thank you Dirk. I'll have a look at that.