28

I'm using Spring since a few months for now, and I thought dependency injection with the @Autowired annotation also required a setter for the field to inject.

So, I am using it like this:

@Controller
public class MyController {

    @Autowired
    MyService injectedService;

    public void setMyService(MyService injectedService) {
        this.injectedService = injectedService;
    }

    ...

}

But I've tried this today:

@Controller
public class MyController {

    @Autowired
    MyService injectedService;

    ...

}

And oh surprise, no compilation errors, no errors at startup, the application is running perfectly...

So my question is, is the setter required for dependency injection with the @Autowired annotation?

I'm using Spring 3.1.1.

Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
Tony
  • 1,246
  • 2
  • 16
  • 29

3 Answers3

42

You don't need a setter with the @Autowired, the value is set by reflection.

Check this post for complete explanation How does Spring @Autowired work

Community
  • 1
  • 1
Arnaud Gourlay
  • 4,646
  • 1
  • 29
  • 35
4

No, if Java security policy allows Spring to change the access rights for the package protected field a setter is not required.

Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
2
package com.techighost;

public class Test {

    private Test2 test2;

    public Test() {
        System.out.println("Test constructor called");
    }

    public Test2 getTest2() {
        return test2;
    }
}


package com.techighost;

public class Test2 {

    private int i;

    public Test2() {
        i=5;
        System.out.println("test2 constructor called");
    }

    public int getI() {
        return i;
    }
}


package com.techighost;

import java.lang.reflect.Field;

public class TestReflection {

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class<?> class1 = Class.forName("com.techighost.Test");
        Object object = class1.newInstance();
        Field[] field = class1.getDeclaredFields();
        field[0].setAccessible(true);
        System.out.println(field[0].getType());
        field[0].set(object,Class.forName(field[0].getType().getName()).newInstance() );
        Test2 test2 = ((Test)object).getTest2();
        System.out.println("i="+test2.getI());

    }
}

This is how it is done using reflection.

Sunny Gupta
  • 6,929
  • 15
  • 52
  • 80