从控制器中删除自动装配并用正常初始化替换它

delete the autowire from controller and replace it with normal initialization

我当前的代码包含@autowired,但我想删除它,然后用代码初始化它。如果您发现我的问题难以理解,请否决我的问题,但请至少发表评论,以便我可以重新编辑,因为我是这个注释内容的新手,并且仍然弄湿了它。

下面显示了我的代码,根据我对自动装配的理解,它从 class "Test" 中获取值并将这些值连接到测试。如果我从代码中删除这个@autowired 会怎么样?我怎样才能让它可执行?我的意思是,如果我删除了@autowired,我怎样才能在同一行中初始化值而不是使用接线注释呢? - 我想尝试这个的原因是为了看看我的理解,同时看到更多不同的例子来提高我的理解

 @Autowired
  @Qualifier("testing")
  Test testing;

我没有预期的结果,因为我只是想了解注释,看看我的理解是否正确。

可以通过三种方式将自动装配的依赖项(使用 spring)注入到 bean 中:

  1. 自动装配字段本身

    @Autowired
    private Test test;
    
    @Autowired
    private SomethingService somethingService;
    
  2. 自动装配 setter

    private Test test;
    private SomethingService somethingService;
    
    @Autowired
    public void setTest(Test test) {
        this.test = test;
    }
    
    @Autowired
    public void setSomethingService(SomethingService somethingService) {
        this.somethingService = somethingService;
    }
    
  3. 自动装配构造函数(不需要注解):

    public class Something {
    
        private Test test;
        private SomethingService somethingService;
    
        public Something(Test test, SomethingService somethingService) {
            this.test = test;
            this.somethingService = somethingService;
        }
    
        ...
    }
    

使用第三种方法的一个好处是,当您构造一个 class 的实例进行测试时,您可以传入任何您想要的依赖项实现。