alt*_*vic 5 java spring spring-boot
我用来@ConditionalOnProperty创建一个FileCompressorbean:
@Bean
@ConditionalOnProperty(prefix = "file.rollover.sink", name = "compress", matchIfMissing = true)
public FileCompressor fileCompressor() {
return new DefaultFileCompressor(...);
}
Run Code Online (Sandbox Code Playgroud)
我想FileCompressor仅在 bean 存在时(null如果file.rollover.sink.compress=false作为方法参数)自动装配 bean。但如果我尝试将其定义为:
@Bean
public RolloverTask rolloverTask(final IntervalCalculator intervalCalculator, final @Autowired(required = false) FileCompressor fileCompressor) {
return new RolloverTask(intervalCalculator, fileCompressor);
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
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'
Run Code Online (Sandbox Code Playgroud)
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(...);
}
Run Code Online (Sandbox Code Playgroud)
matchIfMissing = true有没有没有意义havingValue =。因为如果您没有属性,则会创建 bean,如果您有一个具有任何值的属性,则会创建 bean。
你可以这样解决:
@Autowired(required = false)
private FileCompressor fileCompressor;
@Bean
public RolloverTask rolloverTaskWithCompressor(final IntervalCalculator intervalCalculator, final FileCompressor fileCompressor) {
return new RolloverTask(intervalCalculator, fileCompressor);
}
Run Code Online (Sandbox Code Playgroud)
或者对两个版本有不同的 bean 定义RolloverTask:
@Bean
@ConditionalOnProperty(prefix = "file.rollover.sink", name = "compress", havingValue = "no", matchIfMissing = false)
public RolloverTask rolloverTask(IntervalCalculator intervalCalculator) {
return new RolloverTask(intervalCalculator, null);
}
@Bean
@ConditionalOnProperty(prefix = "file.rollover.sink", name = "compress", havingValue = "yes", matchIfMissing = true)
public RolloverTask rolloverTaskWithCompressor(final IntervalCalculator intervalCalculator, final FileCompressor fileCompressor) {
return new RolloverTask(intervalCalculator, fileCompressor);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7249 次 |
| 最近记录: |