Issue
In spring, we can mark a class as @Configuration
, and use it to configure the beans.
But the bean can also be used as a normal bean, see the example:
@Configuration
@EnableCaching
public class CacheConfig {
private List<GuavaCache> caches = Collections.emptyList();
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(caches);
return cacheManager;
}
public String statistics() {
StringBuilder sb = new StringBuilder();
for (GuavaCache cache : caches) {
sb.append(cache.statistics()).append("\n");
}
return sb.toString();
}
}
You can see we configured a CacheManager
bean in this CacheConfig
, but it also contains a normal statistics
method that we can reference this bean and invoke it.
I just wonder is it the recommended way to use @Configuration
class?
Personally, I would avoid it, because it mixes two responsabilities, "creating beans", "providing some business logic". I prefer creating another bean for the statistics (the code following maybe incorrect, just for demo).
@Configuration
@EnableCaching
public class CacheConfig {
private List<GuavaCache> caches = Collections.emptyList();
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(caches);
return cacheManager;
}
@Bean
public CacheStatistics cacheStatistics() {
return new CacheStatistics(caches);
}
}
class CacheStatistics {
private List<GuavaCache> caches;
public CacheStatistics(List<GuavaCache> caches) {
this.caches = caches;
}
public String statistics() {
StringBuilder sb = new StringBuilder();
for (GuavaCache cache : caches) {
sb.append(cache.statistics()).append("\n");
}
return sb.toString();
}
}
Solution
Basically we used @Configuration to replace .xml files in spring.This files are not used for putting up business logic
So we need to take care if we using @Configuration we just use it for declaring beans.I don't think we put other things there well.
Thanks, Himanshu
Answered By - himanshu bisht
Answer Checked By - Robin (JavaFixing Admin)