Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 805
Anthony Avatar asked Aug 21 '10 06:08

Anthony


People also ask

What is @autowired and how it works?

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.

What is the difference between @bean and @autowired?

@Bean is just for the metadata definition to create the bean(equivalent to tag). @Autowired is to inject the dependancy into a bean(equivalent to ref XML tag/attribute).

Is @autowired dependency injection?

Short answer: Dependency Injection is a design pattern, and @autowired is a mechanism for implementing it.

Does spring @autowired inject beans by name or by type?

if Spring encounters multiple beans with same type it checks field name. if it finds a bean with the name of the target field, it injects that bean into the field.


2 Answers

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.

like image 111
Donal Fellows Avatar answered Sep 29 '22 08:09

Donal Fellows


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

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

like image 36
earldouglas Avatar answered Sep 29 '22 07:09

earldouglas