I found it hard to choose a topic to describe in my first blog post. I wanted it not to be too trivial and too complicated neither. 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 described approach. Java Config might seem to be an overkill in many situations but I hope you will find that post useful anyway. Let’s go!
Inter-bean reference
Imagine we have a following repository:
public class MyRepository {
public String findString() {
return "some-string";
}
}
and a service, that depends on 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";
}
}
First solution is pretty straightforward and it’s called inter-bean reference. MyService bean depends on MyRepository. In order to fulfill this dependency, we pass 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 a following repository, that 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 prefix and suffix are values from external properties file. In order to inject those properties, we will use @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: @Configuration annotation tells Spring that so-annotated class will have one or more bean defined inside. @Bean annotation is a way of telling Spring container to manage the bean returned by so-annotated method. Like in examples above, @Bean methods are generally used inside configuration classes, that are proxied by CGLIB – the result of 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 (like nulls in the example above) you use while calling such methods 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. @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 inter-bean reference is a very nice way of defining bean dependencies inside @Configuration class as long as bean-defining method has no parameters. Otherwise, I choose the below one – read on!
Dependency as @Bean method parameter
Okay, and what if you don’t like passing methods as arguments? Or you have MyRepository bean defined with @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 on parameter name, you can use @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 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 common application context (this is important here!), you can inject the bean like in one of 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 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());
}
}
It’s not all. There is yet another Spring mechanism hidden under the @Import annotation:
@Configuration
@Import({FirstConfiguration.class})
class SecondConfiguration {
...
}
This looks nice, gives you the ability to relate different configurations not necessarily under the same context scope. In this setup you can use autowiring of beans and the configuration class as well (see 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 classes, and bean-definig methods have no parameters – I use inter-bean reference, otherwise – I choose passing bean as method parameter. IDE easy 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 @Import annotation and I pass beans as method paremeters or autowire them.