2

I have some code in my spring project as below

@Component
public class DatabaseAccessUtil
{
    @Autowired
    private DatabaseAccessor databaseAccessor;
}

My concern is how and why @Autowired annotation of spring work without setter method, example:

void setDatabaseAccessor(DatabaseAccessor databaseAccessor)
{
    this.databaseAccessor = databaseAccessor;
}

where is spring's miracle? Thanks

Lam Le
  • 809
  • 8
  • 14

1 Answers1

4

It is because the value of the field is injected via Reflection. Field, Method and Constructor are all descendants of java.lang.reflect.AccessibleObject. This class permits access to its private members by setting the accessible flag to true by calling setAccessible(true).

Here is the actual code from AutowiredBeanPostProcessor that does the actual injection

if (value != null) {
    ReflectionUtils.makeAccessible(field);
    field.set(bean, value);
}

And the source code of ReflectionUtils.makeAccessible(Field)

public static void makeAccessible(Field field) {
    if ((!Modifier.isPublic(field.getModifiers()) ||
            !Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
            Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
        field.setAccessible(true);
    }
}
Bnrdo
  • 5,325
  • 3
  • 35
  • 63