简体   繁体   中英

Spring dependency injection with @Autowired annotation without setter

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.

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

不,如果Java安全策略允许Spring更改受保护包的字段的访问权限,则不需要setter。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM