Issue
There are reasons for adding @Bean on String
You will have to name the bean, and then use the @Qualifier annotation when autowiring referencing that name.
But in the following code, without name attribute
@Configuration
@PropertySource(value = { "classpath:my.properties" })
public class MyEnvironment {
@Value("${MY_NAME}") String MY_NAME;
@Value("${MY_NAME2}") String MY_NAME2;
@Bean
public String getMyName() {
return MY_NAME;
}
@Bean
public String getMyName2() {
return MY_NAME2;
}
}
It's called using method as:
myEnvironment.getMyName();
Isn't @Bean
redundant/irrelevant in this case? also can this convention cause issues? or is there a hidden benefit?
Solution
Considering that Spring's intention is to Inject Dependency, @Bean
in this scenario is definitely redundant.
Since most of your classes with only make use of, (or you may say - depend on), the configuration object myEnvironment
. So it make more sense to inject the MyEnvironment
class, as a single unit, to those classes that rely on it, not the individual String
object.
Though, that depends on how you design your classes and their dependencies. E.g. You can also just injecting those two String values, into the classes that needed it, by using the @Value
directly on those classes without the need to have the MyEnvironment
class at all.
Answered By - Montri M