java - 注解 @Value 在 Spring Boot 中不能正常工作?

标签 java spring spring-boot

上下文:

我使用 @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/

相关文章:

java - 将 json 字符串转换为列表或 map

java - LMAX 颠覆器如何用于股票市场?

java - 使用 hibernate validator 一次验证所有字段

java - Spring Boot Autowired 和 Post Construct 如何工作?

java - 无法通过点击 TemplateApi 端点来查看文档

java - Java 中的泛型方法和类型推断

java - XML 到域对象转换器的 XPath 替代品

java - Spring 启动: MySQLNonTransientConnectionException: Could not create connection

spring - 如何使用 Spring Cloud AWS 从 S3 删除文件?

java - 为什么术语 "unit of work"如此重要,为什么 JDBC AutoCommit 违反了这个模式?