Anthony
Anthony

Reputation: 1685

How does Spring annotation @Autowired work?

I came across an example of @Autowired:

public class EmpManager {
   @Autowired
   private EmpDao empDao;
}

I was curious about how the empDao get sets since there are no setter methods and it is private.

Upvotes: 52

Views: 35952

Answers (4)

MrJavaJEE
MrJavaJEE

Reputation: 41

No need for any setter, you just have to declare the EmpDao class with the annotation @component in order that Spring identifies it as part of the components which are contained in the ApplicationContext ...

You have 2 solutions:

  • To manually declare your beans in the XML file applicationContext :
<bean class="package.EmpDao" />
  • To use automatic detection by seeting these lines in your context file:
<context:component-scan base-package="package" />
<context:annotation-config />

AND to use the spring annotation to declare the classes that your spring container will manage as components:

@Component
class EmpDao {...}

AND to annotate its reference by @Autowired:

@Component (or @Controller, or @Service...)
class myClass {

// tells the application context to inject an instance of EmpDao here
@Autowired
EmpDao empDao;


public void useMyDao()
{
    empDao.method();
}
...
}

Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.

Spring knows the existence of the beans EmpDao and MyClass and will instantiate automatically an instance of EmpDao in MyClass.

Upvotes: 4

Donal Fellows
Donal Fellows

Reputation: 137557

Java allows access controls on a field or method to be turned off (yes, there's a security check to pass first) via the AccessibleObject.setAccessible() method which is part of the reflection framework (both Field and Method inherit from AccessibleObject). Once the field can be discovered and written to, it's pretty trivial to do the rest of it; merely a Simple Matter Of Programming.

Upvotes: 46

krock
krock

Reputation: 29619

Spring uses the CGLib API to provide autowired dependency injection.


References

Further Reading

Upvotes: 1

earldouglas
earldouglas

Reputation: 13473

Java allows you to interact with private members of a class via reflection.

Check out ReflectionTestUtils, which is very handy for writing unit tests.

Upvotes: 7

Related Questions