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