How does @Autowired
annotation work for a private field without a getter and a setter?
How can spring access a private field?

- 441
- 4
- 19

- 2,874
- 3
- 27
- 42
-
http://stackoverflow.com/a/17531269/1297272 – Javier Feb 24 '15 at 11:12
-
1it's `@automagic` because spring uses reflection for it's dependency wiring mechanisms. – vikingsteve Feb 24 '15 at 11:21
-
1Disagree that this is a duplicate, since those questions are purely about reflection. This question is asking essentailly why does the spring framework use reflection in this mechanism – vikingsteve Feb 24 '15 at 11:23
-
It can autowire using constructor and also using the type specifier. – Rajesh Feb 24 '15 at 11:31
3 Answers
It works with reflection. Here you can find an example of how to set public fields. But setting private fields does not make much of a difference
The only difference with a private field is that you will need to set the setAccessible before you are able to read/write to the field. Further, this method can throw a SecurityException. Java Docs

- 654
- 1
- 8
- 22

- 2,643
- 14
- 27
-
8The only difference with a private field is that you will need to set the `setAccessible` before you are able to read/write to the field. Further, this method can throw a `SecurityException`. http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible-java.lang.reflect.AccessibleObject:A-boolean- – PeterK Feb 24 '15 at 11:32
-
@Component
public class A(){}
@Component
public class B(){
@Autowired
private A a;
}
Spring create beans mentioned as @Component. here bean A will be created first and since B is dependent on A, then injection of A to B is done. there's no need for any setters. just @Component is required. Spring uses CGLib for creation of beans using reflection.

- 379
- 1
- 5
Three types of dependency injection
There are at least three ways an object can receive a reference to an external module:
constructor injection: the dependencies are provided through a class constructor.
setter injection: the client exposes a setter method that the injector uses to inject the dependency.
interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

- 786
- 6
- 12