Sometimes you need an instance of class A, but you do not store A in the fields of the class that uses A.
You just need A instance to perform a one-shot operation. Or, you use A instance to obtain an instance of B, and you are storing B in the field.

In those cases, a setter (or constructor) autowire will suit you better.
You will not have unused class-level fields.

Concrete example:
You need to construct RabbitTemplate (an object that sends messages to RabbitMQ) To construct it, you need ConnectionFactory
http://docs.spring.io/spring-amqp/docs/latest_ga/api/org/springframework/amqp/rabbit/core/RabbitTemplate.html#RabbitTemplate-org.springframework.amqp.rabbit.connection.ConnectionFactory-

You do not need to store that ConnectionFactory. In that case, code that looks like this:

Class MyClass {
private RabbitTemplate template;

@Autowired 
void setConnectionFactory(ConnectionFactory c) {
    template=new RabbitTemplate(c);
}
}

...will serve you better than directly autowiring the ConnectionFactory field.

In this example, autowiring at the constructor level would be even better, because your object will always be completely constructed. It will be clear that ConnectionFactory is a mandatory dependency, not an optional one.

Answer from Bartosz Bilicki on Stack Overflow
Top answer
1 of 7
38

Sometimes you need an instance of class A, but you do not store A in the fields of the class that uses A.
You just need A instance to perform a one-shot operation. Or, you use A instance to obtain an instance of B, and you are storing B in the field.

In those cases, a setter (or constructor) autowire will suit you better.
You will not have unused class-level fields.

Concrete example:
You need to construct RabbitTemplate (an object that sends messages to RabbitMQ) To construct it, you need ConnectionFactory
http://docs.spring.io/spring-amqp/docs/latest_ga/api/org/springframework/amqp/rabbit/core/RabbitTemplate.html#RabbitTemplate-org.springframework.amqp.rabbit.connection.ConnectionFactory-

You do not need to store that ConnectionFactory. In that case, code that looks like this:

Class MyClass {
private RabbitTemplate template;

@Autowired 
void setConnectionFactory(ConnectionFactory c) {
    template=new RabbitTemplate(c);
}
}

...will serve you better than directly autowiring the ConnectionFactory field.

In this example, autowiring at the constructor level would be even better, because your object will always be completely constructed. It will be clear that ConnectionFactory is a mandatory dependency, not an optional one.

2 of 7
21

With @Autowired annotation, you don't need a setter method. Once your bean's constructor is done with allocating/creating the object, Spring will scan for this annotation and would inject the object instances that you annotated.

While if you have setter and if you are still using xml config, you would explicitly set properties.

Having said that, You could annotate your constructor and setter method with autowired annotation which i would prefer as this would give me flexibility later on to move away from Spring (although i wont do it).

🌐
Medium
medium.com › @agamkakkar › stop-using-spring-autowired-9ab3d37c044b
Stop using Spring @Autowired. Field Injection, Setter Injection, and… | by Agam Kakkar | Medium
November 8, 2024 - Setter injection is useful in specific scenarios, such as optional dependencies or when a dependency may change during the object’s lifecycle. public class OrderService { private PaymentService paymentService; private NotificationService notificationService; @Autowired public void setPaymentService(PaymentService paymentService) { this.paymentService = paymentService; } @Autowired public void setNotificationService(NotificationService notificationService) { this.notificationService = notificationService; } // business logic methods }
🌐
Baeldung
baeldung.com › home › spring › wiring in spring: @autowired, @resource and @inject
Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
May 11, 2024 - A similar check would be to change the @Component attribute value, autowiredFieldDependency, to another value of our choice and run the test again. A NoUniqueBeanDefinitionException will also be thrown. This exception is proof that if we use an incorrect bean name, no valid bean will be found. That’s how we know the match-by-name execution path was invoked. Setter-based injection for the @Autowired annotation is similar to the approach demonstrated for the @Resource setter-based injection.
🌐
Baeldung
baeldung.com › home › spring › guide to spring @autowired
Guide to Spring @Autowired | Baeldung
February 15, 2024 - As a result, Spring injects fooFormatter when FooService is created. Now let’s try adding @Autowired annotation on a setter method. In the following example, the setter method is called with the instance of FooFormatter when FooService is created:
🌐
CodingNomads
codingnomads.com › spring-autowired-annotation
Spring @Autowired Annotation for Dependency Injections
@Autowired can also be used on setter methods. In the example below, the setter method will be called by Spring and a VideoCard instance will be provided whenever a DesktopComputer is created. This is considered "setter injection".
🌐
Reflectoring
reflectoring.io › constructor-injection
Why You Should Use Constructor Injection in Spring
March 28, 2020 - With setter injection, Spring allows us to specify optional dependencies by adding @Autowired(required = false) to a setter method.
🌐
amitph
amitph.com › home › spring › spring setter dependency injection example
Spring Setter Dependency Injection Example | amitph
November 22, 2024 - Line #38: Setter of DogsService is called. Where instance of DogsDao (created at line #36) is injected. Line #39: No-argument constructor of DogsController is called. Line #40: Setter of DogsController is called.
Find elsewhere
🌐
ConcretePage
concretepage.com › spring › spring-autowired-annotation
Spring @Autowired Annotation
March 13, 2023 - public class Student { @Autowired @Qualifier("add") private Address address; public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } } Here the field address will be autowired only ...
🌐
Spring
docs.spring.io › spring-framework › reference › core › beans › annotation-config › autowired.html
Using @Autowired :: Spring Framework
The default behavior is to treat annotated methods and fields as indicating required dependencies. You can change this behavior as demonstrated in the following example, enabling the framework to skip a non-satisfiable injection point through marking it as non-required (i.e., by setting the required attribute in @Autowired to false):
🌐
Laurspilca
laurspilca.com › comparison-field-constructor-setter-injection
A comparison of field, constructor, and setter injection in Spring – LaurSpilca
But @Inject is pretty rare, so let’s consider @Autowired for our current example. The @Autowired annotation can be used in three ways: annotate the field you want to assign a reference from Spring context (field dependency injection) annotate the constructor of the class and Spring will set the bean references in the constructor’s parameters when calling that constructor (constructor dependency injection) annotate the setter, and Spring will set the reference by calling that specific setter method (setter dependency injection).
🌐
Learnerslesson
learnerslesson.com › Spring › Spring-Autowire-using-Setter-Annotations-XML.htm
Spring - Autowire using Setter - Annotations - XML
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("car") public class Car { Wheel wheel; public Wheel getWheel() { return wheel; } @Autowired public void setWheel(Wheel wheel) { this.wheel = wheel; }
🌐
Spring
docs.spring.io › spring-framework › docs › current › javadoc-api › org › springframework › beans › factory › annotation › Autowired.html
Autowired (Spring Framework 7.0.7 API)
Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public. Config methods may have an arbitrary name and any number of arguments; each of those arguments will be autowired with a matching bean in the Spring container. Bean property setter ...
🌐
TutorialsPoint
tutorialspoint.com › spring › spring_autowired_annotation.htm
Spring - @Autowired Annotation
The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments...
🌐
GeeksforGeeks
geeksforgeeks.org › spring-setter-injection-vs-constructor-injection
Spring - Setter Injection vs Constructor Injection - GeeksforGeeks
January 4, 2025 - This is another way to inject dependencies, done by using setter methods. We annotate a setter method with @Autowired and it will work.
Top answer
1 of 2
2

@Autowired is not the same as @Required.

The @Required-Annotation is specialized for telling Spring that this property has to be injected by the information given in the XML-configuration-file (eager) and not through annotations. And that doesn't matter when you use the @Autowire-Annotation.

The @Autowire-Annotation (as in your code-example), tells the ApplicationContext (a.k.a the Spring-IoC-Containter) to inject the desired dependency. (No matter how, if its by using annotations or the XML-File of the ApplicationContext).

The @Required-Annotation, tells the ApplicationContext that this property has to be mentioned in the XML-file (The XML-File of the ApplicationContext), but the Annotation on its own doesn't tell to inject the dependency. So it is used to check if it is in the XML-configuration file, but not to inject a dependency. The injection is done because the property is mentioned in the XML-file.

So in the end it tells that the injection has to be done because of a configuration in the XML-File. But again: The annotation doesn't tell that the dependency has to be injected, but that it has to be mentioned in the XML-File - which then lets the dependency be injected.

With mentioning the property in a XML-File I mean such a configuration for instance:

<bean id="MyClass" class="com.myclasses.common.MyClass">
     <property name="someProperty" value="ValueThatHasToBeInjected" />
</bean>

So why should I use it over the @Autowired-Annotation?

You should use it when the dependency has to be injected due to the informatoin given in the XML-configuration file.

Can you give me an example?

Well, there is already a very good example on this website. where this is also explained.

2 of 2
1

1) You can think of @Required as a check that the property has been eagerly initialised. In other words it requires that it's been injected via configuration (xml or annotation). If annotation is used then you'll see it alongside @Autowired. If the Bean injected does not exist the application fails to startup with a runtime exception.

2) Nothing more nothing less. @Required is very specific in what it's meant to be: a) only applicable on methods, b) requires the bean or else application runtime error on startup. Again, you need dependency injection either via annotation or xml.

3) Most likely you want to know at startup if a Bean is failed to be injected and for that reason you can have @Required along with @Autowired for expressiveness. Functionality-wise you don't need it if you have @Autowired.

Extra notes:

@Autowired has more functionality on the other side of the coin that is - when you want to achieve laziness. So on a setter method:

  1. as you mentioned @Autowired(required = false)
  2. Can also be paired with @Lazy
  3. you can have @Autowired (without required = false) on a setter method whose param is Java 8's Optional achieving the same effect.