java - 仅当 bean 作为方法参数存在时,Spring 才会 Autowiring

标签 java spring spring-boot

我正在使用 @ConditionalOnProperty 创建一个 FileCompressor bean:

@Bean
@ConditionalOnProperty(prefix = "file.rollover.sink", name = "compress", matchIfMissing = true)
public FileCompressor fileCompressor() {
    return new DefaultFileCompressor(...);
}

我想仅在 FileCompressor bean 存在时 Autowiring 它,null 如果 file.rollover.sink.compress=false 作为方法参数。 但是,如果我尝试将其定义为:

@Bean
public RolloverTask rolloverTask(final IntervalCalculator intervalCalculator, final @Autowired(required = false) FileCompressor fileCompressor) {
    return new RolloverTask(intervalCalculator, fileCompressor);
}

我收到以下错误:

Parameter 1 of method rolloverTask in com.example.FileRolloverSinkConfiguration required a bean of type 'com.example.compressor.FileCompressor' that could not be found.
    - Bean method 'fileCompressor' in 'FileRolloverSinkConfiguration' not loaded because @ConditionalOnProperty (file.rollover.sink.compress) found different value in property 'compress'

如果不存在,我应该对 Autowiring 或传递 null 进行哪些更改?

-- 编辑--

我的解决方案:

private FileCompressor fileCompressor;

@Autowired(required = false)
public void setFileCompressor(final FileCompressor fileCompressor) {
    this.fileCompressor = fileCompressor;
}


@Bean
public RolloverTask rolloverTask(final IntervalCalculator intervalCalculator) {
        log.info("Creating a new rollover task with{} a file compressor", fileCompressor == null ? "out" : "");
        return new RolloverTask(intervalCalculator, fileCompressor);
}

@Bean
@ConditionalOnProperty(prefix = "file.rollover.sink", name = "compress", matchIfMissing = true)
public FileCompressor fileCompressor() {
    return new DefaultFileCompressor(...);
}

最佳答案

我认为你可以使用注释 @ConditionalOnBean@ConditionalOnMissingBean

我没有尝试代码,但它应该是这样的:

@Bean
@ConditionalOnBean(FileCompressor.class)
public RolloverTask rolloverTask(final IntervalCalculator intervalCalculator, final FileCompressor fileCompressor) {
    return new RolloverTask(intervalCalculator, fileCompressor);
}

@Bean
@ConditionalOnMissingBean(FileCompressor.class)
public RolloverTask rolloverTask(final IntervalCalculator intervalCalculator) {
    return new RolloverTask(intervalCalculator, null);
}

关于java - 仅当 bean 作为方法参数存在时,Spring 才会 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41895575/

相关文章:

elasticsearch - Spring Boot Elasticsearch 不起作用

java - Bean 属性 'xxx' 不可读或具有无效的 getter 方法 : Does the return type of the getter match the parameter type of the setter?

java - Java 中的泛型转换

java - 如果出现任何类型的异常,重定向到错误 Controller ?

java - Spring Autowiring 为抽象类提供 null bean

java - 访问ehcache.xml中的spring环境变量

java - 上下文初始化时遇到异常

java - for循环算法的Big-O分析

java - Proguard + Spring Boot + Maven 维护结构

java - 无法使用 OpenCV 打开/查看/抓取/读取 IP 摄像头