Defining Bean Dependencies With Java Config in Spring Framework
I found it hard to choose a topic to describe in my first blog post. I wanted it not to be too trivial, nor too complicated It turned out that there are many basic concepts in Spring Framework that can be confusing. Java-based configuration is one of them. I hear my colleagues asking from time to time about it, and I see numerous questions regarding it on StackOverflow. Nevermind the motivation, below you will find a compact description of how to declare beans with Java Config.
Please note that this post won't cover bean dependencies of different scopes nor discussion on annotations like @Component
, @Service
, @Repository
, etc., that are often a good alternative to the described approach. Java Config might seem to be overkill in many situations, but I hope you will find the post useful anyway. Let's go!
Inter-Bean References
Imagine we have the following repository:
public class MyRepository {
public String findString() {
return "some-string";
}
}
And a service that depends on a repository of that type:
public class MyService {
private final MyRepository myRepository;
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
public String generateSomeString() {
return myRepository.findString() + "-from-MyService";
}
}
The first solution is pretty straightforward, and it's called inter-bean reference. The MyService
bean depends on MyRepository
. In order to fulfill this dependency, we pass the myRepository()
method as a constructor parameter (constructor injection).
@Configuration
class MyConfiguration {
@Bean
public MyService myService() {
return new MyService(myRepository());
}
@Bean
public MyRepository myRepository() {
return new MyRepository();
}
}
Easy, right? Good, let's complicate it a bit. Imagine we have the following repository, which has a few dependencies. To make it clearer, I will use String fields:
public class MyRepository {
private final String prefix;
private final String suffix;
public MyRepository (String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
public String findString() {
return prefix + "-some-string-" + suffix;
}
}
MyService
stays the same. Now we want to create a singleton bean of type MyRepository
, where the prefix and suffix are values from an external properties file. In order to inject those properties, we will use the @Value
annotation.
@Configuration
class MyConfiguration {
@Bean
public MyService myService() {
return new MyService(myRepository(null, null));
}
@Bean
public MyRepository myRepository(@Value("${repo.prefix}") String prefix,
@Value("${repo.suffix}") String suffix) {
return new MyRepository(prefix, suffix);
}
}
Wait, what did I just do? I did a constructor injection with a method having both params equal to null. Here is how it all works: The @Configuration
annotation tells Spring that so-annotated class will have one or more beans defined inside. The @Bean
annotation is a way of telling the Spring container to manage the bean returned by that so-annotated method. Like in the examples above, the @Bean
methods are generally used inside configuration classes, which are proxied by CGLIB — the result of the bean-defining method is registered as a Spring bean, and each call of this method will return the same bean (as long as it is a singleton of course). Thus, thanks to CGLIB, whatever params you use while calling such methods (like nulls in the example above), you will get the proper bean. Remember also that according to CGLIB usage, configuration classes and bean-defining methods must not be private or final.
There is a caveat, though. The @Bean
annotation might be used not only in @Configuration
classes — it can be used in @Component
, for example. Then we are talking about a so-called Lite mode. In this case. there are no proxies created, so method invocations are not intercepted and thus interpreted as a typical Java method invocation.
I think that an inter-bean reference is a very nice way of defining bean dependencies inside a @Configuration
class as long as the bean-defining method has no parameters. Otherwise, I go with the option below — read on!
Dependencies as @Bean Method Parameters
Okay, and what if you don't like passing methods as arguments? Or you have a MyRepository
bean defined with a @Component
annotation or in some other @Configuration
class (but of course in the same context)? It is enough to put your dependency as a method parameter (@Autowired
is not needed!):
@Configuration
class MyConfiguration {
@Bean
public MyService myService(MyRepository myRepository) {
return new MyService(myRepository);
}
}
But, hold on — what if I have several MyRepository
beans? Aha! Spring firstly looks at the type of parameter. If it finds more than one bean of this type, it tries to inject by name (yes, the name of the parameter must match the bean name):
@Configuration
class MyConfiguration {
@Bean
public MyRepository myFirstRepository() {
return new MyRepository("first", "repository");
}
//a bean that will be injected by name into myService
@Bean
public MyRepository mySecondRepository() {
return new MyRepository("second", "repository");
}
@Bean
public MyService myService(MyRepository mySecondRepository) {
return new MyService(myRepository);
}
}
If you don't want to base it on parameter name, you can use the @Qualifier
annotation as well, and it will take precedence over the parameter name:
@Configuration
class MyConfiguration {
//a bean that will be injected by name into myService
@Bean
public MyRepository myFirstRepository() {
return new MyRepository("first", "repository");
}
@Bean
public MyRepository mySecondRepository() {
return new MyRepository("second", "repository");
}
@Bean
public MyService myService(@Qualifier("myFirstRepository") MyRepository someRepository) {
return new MyService(someRepository);
}
}
@Configuration Composition
You may now wonder what to do when you have configuration spread over numerous @Configuration
classes and you want to set dependencies among them. Let's consider the following classes:
@Configuration
class FirstConfiguration {
@Bean
public FirstService firstService() {
return new FirstService();
}
}
@Configuration
class SecondConfiguration {
@Bean
public SecondService secondService() {
return new SecondService();
}
}
Now imagine that SecondService becomes dependent on FirstService
. If both configurations are settled in a common application context (this is important here!), you can inject the bean like in one of the previous examples:
@Configuration
class SecondConfiguration {
@Bean
public SecondService secondService(FirstService firstService) {
return new SecondService(firstService);
}
}
@Configuration
is meta-annotated with @Component
, which means that the class will be component scanned and you can benefit from the DI concepts brought in by Spring. It means you can also autowire your bean this way:
@Configuration
class SecondConfiguration {
@Autowired
private FirstService firstService;
@Bean
public SecondService secondService() {
return new SecondService(firstService);
}
}
As I mentioned before, @Configuration
is a @Component
. Thus, you can inject it as if it is a regular bean and call its methods in order to retrieve beans (you will inject a CGLIB proxy!).
@Configuration
class SecondConfiguration {
@Autowired
private FirstConfiguration firstConfiguration;
@Bean
public SecondService secondService() {
return new SecondService(firstConfiguration.firstService());
}
}
That's not all. There is yet another Spring mechanism hidden under the @Import
annotation:
@Configuration
@Import({FirstConfiguration.class})
class SecondConfiguration {
...
}
This looks nice and gives you the ability to relate different configurations that are not necessarily under the same context scope. In this setup, you can use the autowiring of beans and the configuration class as well (see the two previous code snippets).
Conclusions
Defining bean dependencies is a very basic concept of Spring Framework, but as you could see here, there are lots of possibilities to do it, and there are enough approaches to get confused. Which to choose, which is the best, which looks nice, and which is ugly — it depends on the situation and personal (or team) preferences. How do I do it?
- When I have bean definitions inside one configuration class, and bean-definig methods have no parameters, I use inter-bean references. Otherwise, I choose passing a bean as a method parameter. Easy IDE navigation is not as vital as good-looking code.
- When I have two
@Configuration
classes inside a common context, I pass beans as method paremeters or autowire them. - When I have two
@Configuration
classes in separate contexts, I use an@Import
annotation and I pass beans as method paremeters or autowire them.