In this post under Spring Core, I will explain with example the purpose of “required” attribute of “@Autowired” annotation.
When we tell Spring framework to wire two beans say “Bean2” to “Bean1” as shown below
package package20;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Bean1 {
@Autowired
private Bean2 bean2;
public Bean2 getBean2() {
return bean2;
}
public void setBean2(Bean2 bean2) {
this.bean2 = bean2;
}
}
package package20;
@Component
public class Bean2 {
}
We are saying to Spring framework, that when creating “Bean1” instance, if “Bean2” instance is not found or not created then don’t proceed with instantiation of “Bean1”.
In other words, we are saying Spring framework, that for successful creation of “Bean1” instance, we need “Bean2” instance also.
So if “Bean2” instance is not found or not created, then Spring framework will throw “NoSuchBeanDefinitionException” exception.
This is default behavior of “@Autowired” annotation.
We can change this default behavior, that is we can tell Spring framework, that if “Bean2” instance is not found or not created, you continue creating “Bean1” instance.
This can be done with “required” attribute of “@Autowired” annotation as shown below
Bean1
1 package package20;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.stereotype.Component;
5
6 @Component
7 public class Bean1 {
8 @Autowired(required = false)
9 private Bean2 bean2;
10
11 public Bean2 getBean2() {
12 return bean2;
13 }
14
15 public void setBean2(Bean2 bean2) {
16 this.bean2 = bean2;
17 }
18 }
Bean2
package package20;
public class Bean2 {
}
By default “required” attribute value is true, which makes the Spring framework throw “NoSuchBeanDefinitionException” exception when a dependent bean is not found.
In the above code at line 8, I have added “@Autowired” annotation and changed the value of “required” to false.
As a result, if “Bean2” is not found or not created, the Spring framework doesn’t throw any exception it just creates an instance of “Bean1” with “bean2” property set to null.
Please note that I didn’t added “@Component” annotation to “Bean2” class. This is done intentionally to make the Spring framework not create an instance of “Bean2”.
Below is the complete main class for your reference
Main Class
package package20;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "package20")
public class Example20 {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example20.class);
Bean1 bean1 = applicationContext.getBean(Bean1.class);
System.out.println(bean1.getBean2());
}
}