Home > other >  How to create conditional bean to be used for only one bean
How to create conditional bean to be used for only one bean

Time:04-22

I created a bean on my Configuration class but I want only one bean should use this custom bean. I don't want any other bean can use this.

Here's my Configuration class;

@Configuration
public class ProcessorConfig {

    @Bean
    public List<Processor> processors(){
        SSto processor1 = new SSto();
        CSto processor2 = new CSto();
        DGTu processor3 = new DGTu();
        EGam processor4 = new EGam();

        return of(processor1, processor2, processor3, processor4);
    }
}

And this is the bean that I want to use this custom bean.

@Component
@RequiredArgsConstructor
public class ProcessorDecorator {

    private final List<Processor> processors;

    public void apply(Ga ga) {
        this.processors.forEach(processor -> processor.apply(ga));
    }

}

I just want this ProcessorDecorator class to inject List processors. No other class can inject this List processors. How can I achieve this?

CodePudding user response:

if you want only to ProcessorDecorator to only have this list of processors why not declare those processors in ProcessorDecorator ?

other way would be specifing custom name for bean @Bean(name = "decoratorProcessors")

and adding qualifier in ProcessorDecorator @Qualifier("decoratorProcessors") but other classes injecting processors should probably have @Qualifier("processors") to block them from injecting decoratorProcessors

  • Related