Spring @Profile and auto-matching

I am using Spring framework (ver 3.2) and after some refactoring in my application, I ran into problem with configuring Autowiring with profile.

Let's say I have one interface that is implemented by two classes. These classes implement many methods depending on your environment settings. Actually I have 3 different profile profiles profile1, profile2 and profile3. Using profiles works well, but this is the first time I have a small problem here because the class cannot be entered in a 2 candidate search.

public interface Iexample {
  public void doSomething();
}

@Profile("profile1")
public class classA implements Iexample {
  doSomething(){..}
}

@Profile("{profile2, profile3}")    
public class ClassB implements Iexample {
  doSomething(){..}
}

public class Test1 {

@Autowired
Iexample example; //Should use implementation based on profile1 or profile2

}

public class Test2 {

@Autowired
Iexample example; //Should use implementation based on profile3 only

}

      

The current property is configured:

spring.profiles.active= profile1,profile3

      

Possible configuration

  • profile1, profile3
  • profile2, profile3

Is it possible to specify which class should be implemented anyway (something like @Qualifier)?

Why not @ActiveProfiles?

ActiveProfiles is a class-level annotation that is used to declare which active profiles of a bean definition to use when loading the ApplicationContext for test classes.

In this case, I need to know if there is a way to specify which class, depending on the profile, should be injected.

Please see the example below.

@Controller
public class exampleController {
    @Autowired
    // Suppose that this can be possible
    @Qualifier("{profile1, profile2}")
    Iexample example
}

      

If the Qualifier listed this way can work, then I should be able to fix the problem.

thank

+3


source to share


1 answer


You can mark the bean with the @Primary annotation to indicate that it should take precedence as a self-timer candidate. The Javadoc is for Spring 4, but the documentation for Spring 3.2 also mentions this annotation.



0


source







All Articles