MrSir
MrSir

Reputation: 596

Spring @Primary not working

I have a simple configuration

@Configuration
public class ConfigurationUtil {

    @Bean
    @Primary
    @Profile("apple")
    Fruit apple(){
        return new Apple();
    }

    @Bean
    @Profile("banana")
    Fruit banana(){
        return new Banana();
    }

}

In application.properties if I use spring.profiles.active=apple or banana the proper one gets autowired but if i remove it I have the error:

Description:

Parameter 0 of constructor in basicspringexample.basicspringexample.MainUtil required a bean of type 'basicspringexample.basicspringexample.comp.Fruit' that could not be found.

Action:

Consider defining a bean of type 'basicspringexample.basicspringexample.comp.Fruit' in your configuration.

The bean gets called by a simple @Service annotated class

@Service
public class MainUtil {

    private Fruit fruit;

    @Autowired
    public MainUtil(Fruit fruit) {
        this.fruit = fruit;
        System.out.println(fruit.print());
    }

} 

Isn't @Primary supposed to display the annotated bean when there's not specification in spring.profiles.active ? Or am I doing something wrong ?

Upvotes: 2

Views: 9974

Answers (1)

Sync
Sync

Reputation: 3777

Why isn't @Primary working as I expect?

First, the bean configurations gets filtered by @Profile. Only after this, @Primary will kick in if multiple beans of the same type is found.

This is why, after the filtering of no profile, no bean of type Fruit is left and Spring will complain.

Upvotes: 3

Related Questions