【发布时间】:2019-09-09 09:43:33
【问题描述】:
在一个基本的 Spring Boot 应用程序中,我有这个组件:
@Component
public class TheComponent {
public String getKey() {return "value";}
}
由服务使用。如果我这样设计我的服务:
@Service
public class TheService {
@Autowired
private TheComponent theComponent;
private final String keyValue = theComponent.getKey();
private TheService() {}
}
然后 Spring Boot 不会构建,因为 theComponent 触发了 NullPointerException。
如果我这样设计:
@Service
public class TheService {
private String keyValue;
private TheService(TheComponent theComponent) {
keyValue = theComponent.getKey();
}
}
然后 SonarLint 告诉我应该删除这个未使用的私有“TheService”构造函数。
是否有一个解决方案既适合 Spring 又适合 SonarLint,使用私有构造函数?
【问题讨论】:
-
问题是为什么TheComponent不能自动连线,你是使用组件扫描还是如何将它设置为bean?
-
抱歉,我无法回答您的问题。我只能说我在没有更改任何配置的情况下使用了 Spring initializr。我认为它不能自动装配,因为
keyValue初始化发生在自动装配之前(source)。
标签: java spring reflection jvm sonarlint