繁体   English   中英

@Autowired与@Autowired with Setter

[英]@Autowired vs @Autowired with Setter

我有一个与Web插件一起使用的spring boot应用程序。

一堂课我有:

package com.test.company
@Component
@RestController
public class CompanyService {

   @Autowired
   private MongoTemplate mongoTemplate;

   @Autowired
   private Environment env;

在另一堂课中,我有:

package com.test.company
@Component
@RestController
public class CustomerSignUpService {

   private static MongoTemplate mongoTemplate;

   @Autowired
   private Environment env;

   @Autowired
   public void setMongoTemplate(MongoTemplate mongoTemplate) {
          this.mongoTemplate = mongoTemplate;
   }

这两个类都可以工作,但是如果我像在CompanyService类中一样尝试将mongo注入CusomterSignUpService类中,则可以很好地注入env ,但是mongo不能注入,并且如果尝试使用它,则会得到空指针异常。

有什么想法吗? Main软件包是com.test

我相信您的Controller可能需要看起来像(从属性中删除了static ):

package com.test.company
@Component
@RestController
public class CustomerSignUpService {

   @Autowired
   private MongoTemplate mongoTemplate;

   @Autowired
   private Environment env;

   ...
   ...
}

您可以在属性和设置器中使用@Autowired ,但是您的属性必须是实例变量,而不是静态变量。

这样做,您的代码应该可以正常运行:

package com.test.company
@Component
@RestController
public class CustomerSignUpService {

   private MongoTemplate mongoTemplate;

   @Autowired
   private Environment env;

   @Autowired
   public void setMongoTemplate(MongoTemplate mongoTemplate) {
          this.mongoTemplate = mongoTemplate;
   }

请注意, static保留字取自您的属性声明。

从属性中删除静态并尝试不使用它

package com.test.company
@Component
@RestController
public class CustomerSignUpService {

   @Autowired
   private MongoTemplate mongoTemplate;

   @Autowired
   private Environment env;

   ...
   ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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