Reputation: 792
Say I have the following
public abstract class MyClass {
@Resource
protected MyService myService;
doSomething() {
return myService.doSomething();
}
}
public class MyServiceV1 implements MyService {}
public class MyServiceV2 implements MyService {}
public class MyClassV1 extends MyClass {
//WANT TO USE MyServiceV1 implementation
}
public class MyClassV2 extends MyClass {
//WANT TO USE MyServiceV2 implementation
}
I am unable to specify the service implementation that I want to use in each subclass. I have considered using @Qualifier but I would have to re-declare the property in each child class and use it there, and hope that it overrides the parent.
The purpose of these classes is to provide two versions of an API at the same time. So both versions will be active simultaneously.
It does feel partially that this is an anti pattern in terms of how spring is meant to inject beans, so I am open to other approaches.
Upvotes: 0
Views: 2255
Reputation: 311
I think you can try to use Constructor injection to set a particular service in your classes. Smth like this:
public abstract class MyClass {
protected MyService myService;
doSomething() {
return myService.doSomething();
}
}
class MyClassV1 extends MyClass {
MyClassV1(MyService myService) {
this.myService = myService;
}
}
class MyClassV2 extends MyClass {
MyClassV2(MyService myService) {
this.myService = myService;
}
}
@Bean
MyClassV1 myClassV1() {
return new MyClassV1(myServiceV1());
}
@Bean
MyClassV1 myClassV2() {
return new MyClassV2(myServiceV2());
}
@Bean
MyServiceV1 myServiceV1() {
return new MyServiceV1();
}
@Bean
MyServiceV2 myServiceV2() {
return new MyServiceV2();
}
or setter injection:
public abstract class MyClass {
private MyService myService;
public void setMyService(MyService myService) {
this.myService = myService;
}
}
@Component
public class MyClass1 extends MyClass {
@Autowired @Qualifier("myService1")
@Override
public void setMyService(MyService myService) {
super.setMyService(myService);
}
}
@Component
public class MyClass2 extends MyClass {
@Autowired @Qualifier("myService2")
@Override
public void setMyService(MyService myService) {
super.setMyService(myService);
}
}
Upvotes: 1