【发布时间】:2019-04-03 05:34:19
【问题描述】:
上下文:
我使用@Scheduled 注释处理报告,当从Service 属性调用Component 时,即使它物理存在于.properties 中并打印在@PostConstruct 中,也没有使用@Value 注释进行初始化。
描述:
ReportProcessor 接口和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 中进行了研究,但到目前为止还没有一个想法为什么它会以这种方式工作以及有什么解决方案?
【问题讨论】:
标签: java spring spring-boot