Autowiring Optional beans

In this post under Spring Core, I will show with example how to use Java’s Optional class to declare a bean (to be injected) as optional.

In one of my previous post under Spring Core, I showed you about “required” attribute in “@Autowired” annotation.

For recap, “@Autowired” annotation has only one attribute named “required” whose value dictates whether the bean injection to the composing bean is required for the creation of the composing bean.

Lets take an example, if we define that bean B is to be injected in A with the help of “@Autowired” annotation. Then bean A is dependee object and bean B is dependent object. If the “required” attribute
is “false”. Then when creating an instance of bean A if the instance of bean B is not found or not created yet, this will not prevent the instantiation of bean A. An instance of bean A will be created
with B pointing to null. If the “required” attribute is “true”. Then when creating an instance of bean A if the instance of bean B is not found or not created yet, then instantiation of bean A fails
throwing an exception.

The “required” attribute in “@Autowired” annotation is Spring’s way of indicating whether the dependent bean is optional or not.

We can achieve the same thing with the help of Java’s Optional class.

For our example, I will create the below bean

Bean1 class

package package24;

public class Bean1 {
}

Below is the main class into which the dependent bean “Bean1” has to be injected.

Main class

1  package package24;
2  
3  import org.springframework.beans.factory.annotation.Autowired;
4  import org.springframework.context.ApplicationContext;
5  import org.springframework.context.annotation.AnnotationConfigApplicationContext;
6  import org.springframework.context.annotation.ComponentScan;
7  import org.springframework.context.annotation.Configuration;
8  import java.util.Optional;
9  
10 @Configuration
11 @ComponentScan(basePackages = "package24")
12 public class Example24 {
13     @Autowired
14     private Optional<Bean1> bean1Optional;
15 
16     public static void main(String[] args) {
17         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example24.class);
18         Example24 example = applicationContext.getBean(Example24.class);
19         System.out.println(example.bean1Optional);
20     }
21 }

In the above code at line 14, I created a private field of type Optional named “bean1Optional”.

In this way we are telling Spring framework that when creating a instance of “Example24” bean if you don’t find an instance of “Bean1” proceed with the instantiation of “Example24” without throwing
any exception and set its property “bean1Optional” to Optional.empty instead of null.

Leave a comment