4

I need to autowire fields based on the spring.profiles.active property. The service is only created based on the profile but the since the service is autowired in other classes I am unable to use the @Profile annotations.

Is there a way to autowire fields based on profile.

unnik
  • 1,123
  • 5
  • 18
  • 37

1 Answers1

1

You can create different services implementations per profiles.

In the example below I used mockito to mock the dataSource bean

Ex.

 @Configuration
    @ComponentScan
    class YourConfig {

        @Profile("production")
        @Qualifier("datasource")
        @Bean
        public DataSource dataSourceProduction(){
           return new DataSourceProduction()
        }

        @Profile("development")
        @Qualifier("datasource")
        @Bean
        public DataSource dataSourceDevelopment(){
           return mock(DataSourceProduction.class);
        }
  • Wanted to avoid creating a mock.But thanks i guess I would have to do the same. – unnik Mar 26 '16 at 06:01
  • depending on what you're trying to accomplish you don't have to create a mock like this... but the original question is unclear enough to call this wrong. – xenoterracide Aug 14 '18 at 21:18
  • 5
    The question is how to tell spring: hey spring autowire this field in my class only when profile X is activated. – Rafik EL YAAGOUBI Jun 04 '19 at 13:40