Reputation: 6622
Suppose I have this service bean:
@Service
public class MyService{
private final HashMap<String,String> values;
...
}
with the values being:
com.foo:
values:
a: world
b: helo
I may want to create it inside of a configuration:
@Configuration
@ConfigurationProperties(prefix="com.foo")
public class MyConf{
private Map<String, String> values;
@Bean
public MyService myService(){
return new MyService(values);
}
}
But I fear that spring could do something strange like creating 2 beans or dunno what...is this a good practice or should I just move @ConfigurationProperties inside of the @Service itself?
Upvotes: 0
Views: 164
Reputation: 534
You can inject your configuration directly into your Service
@Service
public class MyService{
private final MyConf conf;
public MyService(MyConf conf) {
this.conf = conf;
}
}
And remove the @Bean annotation from MyConf allong with myservice method.
Upvotes: 1
Reputation: 1112
If you want to use your properties values in your Service class (or anywhere else) you should just inject it :
@Service
public class MyService{
@Autowired
private MyConf myConf;
}
Upvotes: -1
Reputation: 400
You should not do that, as it will create two beans of the same type.
In your case, you have not mentioned different names for the beans
so it will override if spring.main.allow-bean-definition-overriding=true
else it will fail.
PS: For @Service
annotation to create a bean, the class package should be configured in the @ComponentScan
or in the base scan package
Upvotes: 0