Answer the question
In order to leave comments, you need to log in
How to replace one implementation with another in the list of similar beans?
Hello.
I stumbled upon this case and thought about it.
See. I have a SimpleBean interface, for example.
package com.example.beans;
public interface SimpleBean {
String getName();
}
package com.example.beans;
import org.springframework.stereotype.*;
@Component
public class FirstBean implements SimpleBean {
@Override
public String getName() {
return "First Bean";
}
}
package com.example.beans;
import org.springframework.stereotype.*;
@Component
public class SecondBean implements SimpleBean {
@Override
public String getName() {
return "Second Bean";
}
}
package com.example.beans;
import org.springframework.stereotype.*;
@Component
@Primary
public class ThirdBean extends FirstBean {
@Override
public String getName() {
return "I'm inherited " + super.getName() + " and my name is Third Bean";
}
}
package com.example.controllers;
import com.example.beans.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@Controller
public class DemoController {
private List<SimpleBean> myBeans;
/** */
@Autowired
public DemoController(List<SimpleBean> myBeans) {
this.myBeans = myBeans;
}
/** */
@RequestMapping("/")
@ResponseBody
public String hello() {
StringBuilder beansNames = new StringBuilder();
myBeans.forEach(bean -> beansNames.append(bean.getName()).append("\n"));
return beansNames.toString();
}
}
Answer the question
In order to leave comments, you need to log in
There is an annotation @Conditional for this. If Spring Boot is used, then it has @ConditionalOnMissingClass, which allows you to specify that the marked bean should be created if the specified class is not found:
@ConditionalOnMissingClass(ThirdBean.class)
@Component
public class FirstBean implements SimpleBean {
@Override
public String getName() {
return "First Bean";
}
}
Profiles don't work?
Annotate your implementers
with @Profile("SimpleBean-third")
And specify active profiles on startup, the corresponding SimpleBean implementation will be injected.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question