18

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

Parth Sharma
  • 441
  • 4
  • 19
Vishnudev K
  • 2,874
  • 3
  • 27
  • 42

3 Answers3

21

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

Akhil Surapuram
  • 654
  • 1
  • 8
  • 22
wastl
  • 2,643
  • 14
  • 27
  • 8
    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`. 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
  • right, forgot about the SecurityException, thanks. – wastl Feb 24 '15 at 11:32
0
@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.

anurag gupta
  • 379
  • 1
  • 5
-1

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.

Rajesh
  • 786
  • 6
  • 12