我有一个spring启动应用程序,我正在Web插件中使用它。
在一节课上,我有:
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。
发布于 2018-08-09 04:34:33
我认为您的Controller可能需要如下所示(从属性中删除static ):
package com.test.company
@Component
@RestController
public class CustomerSignUpService {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private Environment env;
...
...
}发布于 2018-08-09 04:49:03
您可以在属性和设置器中使用@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保留字取自您的属性声明。
发布于 2019-02-07 08:06:54
从属性中移除static并在不使用它的情况下尝试
package com.test.company
@Component
@RestController
public class CustomerSignUpService {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private Environment env;
...
...
}https://stackoverflow.com/questions/51755118
复制相似问题