【问题标题】:Spring dependency injection with @Autowired annotation without setter带有@Autowired注解的Spring依赖注入,没有setter
【发布时间】:2012-04-25 20:11:46
【问题描述】:

几个月以来我一直在使用 Spring,我认为带有 @Autowired 注释的依赖注入也需要一个 setter 来注入字段。

所以,我是这样使用它的:

@Controller
public class MyController {

    @Autowired
    MyService injectedService;

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

    ...

}

但我今天已经试过了:

@Controller
public class MyController {

    @Autowired
    MyService injectedService;

    ...

}

哦,惊喜,没有编译错误,启动时没有错误,应用程序运行完美......

所以我的问题是,使用 @Autowired 注释进行依赖注入需要 setter 吗?

我正在使用 Spring 3.1.1。

【问题讨论】:

  • 好像你已经回答了自己的问题。

标签: java spring dependency-injection autowired


【解决方案1】:

@Autowired 不需要设置器,值是通过反射设置的。

查看这篇文章以获得完整的解释How does Spring @Autowired work

【讨论】:

  • 别忘了把链接的帖子放上去;)
  • 字段可以是私有的,Spring Autowired 也可以在没有 setter 的情况下工作。
【解决方案2】:

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

【讨论】:

    【解决方案3】:
    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());
    
        }
    }
    

    这是使用反射完成的。

    【讨论】:

      猜你喜欢
      • 2017-04-26
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 2012-07-24
      • 2021-11-05
      • 1970-01-01
      • 2017-06-06
      相关资源
      最近更新 更多