上下文:
我使用 @Scheduled
注释处理报告,当从 Service
属性调用 Component
时,未使用 @Value
初始化> 注释,即使它实际存在于 .properties
中并在 @PostConstruct
中打印出来。
描述:
ReportProcessor
接口(interface)和InventoryReportProcessor
实现:
@FunctionalInterface
interface ReportProcessor {
public void process(OutputStream outputStream);
}
@Component
public class InventoryReportProcessor implement ReportProcessor {
@Value("${reportGenerator.path}")
private String destinationFileToSave;
/*
@PostConstruct
public void init() {
System.out.println(destinationFileToSave);
}
*/
@Override
public Map<String, Long> process(ByteArrayOutputStream outputStream) throws IOException {
System.out.println(destinationFileToSave);
// Some data processing in here
return null;
}
}
我用它从
@Service
public class ReportService {
@Value("${mws.appVersion}")
private String appVersion;
/* Other initialization and public API methods*/
@Scheduled(cron = "*/10 * * * * *")
public void processReport() {
InventoryReportProcessor reportProcessor = new InventoryReportProcessor();
Map<String, Long> skus = reportProcessor.process(new ByteArrayOutputStream());
}
}
我的困惑来自于 Service
中的 @Value
工作正常但在 @Component
中它返回 null
除非调用 @PostConstruct
。此外,如果调用 @PostConstruct
,则该值在类代码的其余部分仍为 null
。
我找到了类似的 Q&A我在 Srping docs 做了研究但到目前为止还不知道为什么它会这样工作以及有什么解决方案?
最佳答案
您需要 Autowiring 组件以使您的 spring 应用程序知道该组件。
@Service
public class ReportService {
@Value("${mws.appVersion}")
private String appVersion;
/* Other initialization and public API methods*/
@Autowired
private ReportProcessor reportProcessor;
@Scheduled(cron = "*/10 * * * * *")
public void processReport() {
//InventoryReportProcessor reportProcessor = new InventoryReportProcessor();
Map<String, Long> skus = reportProcessor.process(new ByteArrayOutputStream());
}
}
关于java - 注解 @Value 在 Spring Boot 中不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55487709/