Home > Net >  Spring profile annotation multiple beans
Spring profile annotation multiple beans

Time:11-30

Let's say I have a library (I cannot change it). There is a class Consumer that uses a spring component of class A.

@Component
public class Consumer{
   @Autowired
   private A a;
}

In my configuration class I want to define two beans of same class A depending on the profile.

@Configuration
public class Config {
    
    @Bean
    @Profile("!dev")
    A a1(){
        return new A();
    }
    
    @Bean
    @Profile("dev")
    A a2(){
        return new A();
    }
}

But when I start the app, I get next exception

Parameter 1 of constructor in sample.Consumer required a single bean, but 2 were found:

I can't get how to fix that. I've tried to create 2 separate configs for that with profile annotation and single bean there, but it also did not work. Marking one bean @Primary also does not help.

Do you guys know how to fix that? Thanks!

UPD.

Let me make it more specific. That class is a part of dynamodb spring starter. Consumer - DynamoDBMapperFactory. My bean - DynamoDBMapperConfig. So I want to have 2 versions of DynamoDBMapperConfig in my app.

CodePudding user response:

You need to stop scanning package where Consumer declared.

CodePudding user response:

@Profile behaves differently if it's applied to the @Bean annotated method.

From Profile doc.:

Use distinct Java method names pointing to the same bean name if you'd like to define alternative beans with different profile conditions

This means, you should do:

@Configuration
public class Config {
    
    @Bean("a")
    @Profile("!dev")
    A a1(){
        return new A();
    }
    
    @Bean("a")
    @Profile("dev")
    A a2(){
        return new A();
    }
}

Note the same bean names.

  • Related