Logic in @Configuration

what do you think, is it permissible to use logic in a class marked as @Configuration, given that this logic is applied only 1 time at the start of the application. For example: We want to configure Caches and for this, we need to do a couple of injections in the class marked as @Configuration, write some methods to create caches and add @PostConstract.

How legal is it to write such a thing not in @Service or @Component, but in @Configuration? And if it's bad, then why?

@Configuration
public class SomeClass {

@Resource
private SomeCacheManager someCacheManager;

@Resource
private SomeCacheEvictor someCacheEvictor;


@PostConstruct
public void init(){
    createCache("Some cache");
    createCache("Other");
    createCache("More");
    ...
}


public void createCache(String cacheName){
    /*
    Some code to create cache
     */
}

}

Upvotes: 1

Views: 530

Answers (2)

aviad
aviad

Reputation: 8278

This can get highly-subjective. However, in my opinion the Configuration should be straight-forward and non-conditional. The logic that controls dynamic types as well as what to inject should be exported to Factory beans. Here is an example https://howtodoinjava.com/spring-core/how-to-create-beans-using-spring-factorybean/amp/

Upvotes: 1

Andrew
Andrew

Reputation: 49606

Try to keep your @Configuration beans as clear as possible. Configurations are usually used to define a set of other @Beans and having "a couple of injections" may make it unclear which @Beans require which injections.

There is an option to inject dependencies through method parameters. I think it's always a better alternative.

@Bean
public Caches getCaches(DependencyA a, DependencyB b) { ... }

DependencyA wouldn't appear for the whole configuration, only for a very restricted scope where it's actually needed.

How legal is it to write such a thing not in @Service or @Component, but in @Configuration?

I see nothing wrong with it. Try to employ the approach I mentioned above. If your logic doesn't fit into a method, or the dependencies specified as parameters aren't enough, you probably do something wrong.

Update:

@PostConstruct is a bad idea. It's a callback that the configuration class's been created. It's a general piece for all the beans defined in the class. It's not meant to start constructing an arbitrary-selected bean.

Upvotes: 0

Related Questions