4

I have 2 classes implementing InterfaceA

@Service("classA")
class ClassA implements InterfaceA

@Service("classB")
class ClassB implements InterfaceA

I need to load both beans. In class C and D, though, I need to specify the bean that I need

class ClassC {
    @Autowired
    @Qualifier("classA")
    private InterfaceA interf;
}

class ClassD {
    @Autowired
    @Qualifier("classA")
    private InterfaceA interf;
}

However, I have 2 profiles, profile1 and profile2. If i use -Dspring.profiles.active=profile1, I should be using qualifier "classA" for classC and classD. If i use -Dspring.profiles.active=profile2, I should use "classB" as qualifier. Also, another ClassE should always use classB regardless of the profile. Can you please advise how should I do it?

iPhoneJavaDev
  • 821
  • 5
  • 33
  • 78

2 Answers2

1

So this is how I did it. I created a configuration class

@Configuration
public class ConfigClass {
    @Autowired
    private ClassB classB;

    @Profile("profile1")
    @Qualifier("myclass")
    @Bean
    private InterfaceA classAtProfile1() {return new ClassA();}

    @Profile("profile2")
    @Qualifier("myclass")
    @Bean
    private InterfaceA classAtProfile2() {return classB;}
}

class ClassA implements InterfaceA

@Service("classB")
class ClassB implements InterfaceA

This way, I can autowire InterfaceA based on profile

@Autowired
@Qualifier("myclass")
private InterfaceA myclass;

While ClassE can still refer to classB

@Component
public class ClassE {
    @Autowired
    ClassB classB;
    ...
}
iPhoneJavaDev
  • 821
  • 5
  • 33
  • 78
-1

Define 2 configuration java files:

class ClassA implements InterfaceA

class ClassB implements InterfaceA

Sample config file 1:

Profile1Config.java

 @Configuration
 @Profile("profile1")
 public class Profile1Config {
    @Bean
    public InterfaceA interfaceA() {
       return new ClassA();
    }
 }

Sample config file 2:

Profile1Config.java

 @Configuration
 @Profile("profile2")
 public class Profile2Config {
    @Bean
    public InterfaceA interfaceA() {
       return new ClassB();
    }
 }

And wherever you want to use this:

class ClassC {
   @Autowired
   private InterfaceA interf;
}

class ClassD {
    @Autowired
    private InterfaceA interf;
}

Key point to note: 1. @Qualifier was not required. 2. @Profile is mentioned at the Java Configuration class. 3. @Service was removed from classA and classB rather defined in Config* classes now.

Himanshu Bhardwaj
  • 4,038
  • 3
  • 17
  • 36