3 回答
TA贡献1111条经验 获得超0个赞
我可以想到两种方法。第一种方法是命名类(在 @Component 之后)并使用上下文,尝试获取 bean。您还可以使用 @Qualifier 命名 bean
@Component("A")
public class A{
public String wish(int timeHr){
//some logic of time based wish
return "Hello A"+" good morning";
}
@Component("B")
public class B{
public String wish(int timeHr){
//some logic of time based wish
return "Hello B"+" good morning";
}
}
@Component("C")
public class C{
public String wish(int timeHr){
//some logic of time based wish
return "Hello C"+" good morning";
}
}
@Service
public class MyService{
@Autowired
private ApplicationContext context;
void myMethod() {
A a = (A) context.getBean("A");
System.out.println(a.wish(123));
}
}
第二种方法是让你所有的愿望类实现一个接口并遍历这个接口的所有实现 bean 并找到正确的 bean
@Component
public class A implements Wisher{
public String wish(int timeHr){
//some logic of time based wish
return "Hello A"+" good morning";
}
@Component
public class B implements Wisher{
public String wish(int timeHr){
//some logic of time based wish
return "Hello B"+" good morning";
}
}
@Component
public class C implements Wisher{
public String wish(int timeHr){
//some logic of time based wish
return "Hello C"+" good morning";
}
}
public interface Wisher{ public String wish(int time); }
@Service
public class MyService{
@Autowired
private List<Wisher> wishers;
void myMethod() {
String requiredClassName = "A";
Wisher requiredWisher = null;
for (int i = 0; i < wishers.length(); i++) {
Wisher w = wishers.get(i);
if (w.getClass().getName().equals(requiredClassName)) {
requiredWisher = w;
break;
}
System.out.println(w.wish(123));
}
}
}
TA贡献1812条经验 获得超5个赞
考虑到您正在使用 Spring 实现,所有 bean 都将是 Singleton,并且这些 bean 将在 App 启动时(加载 ApplicationContext 时)进行初始化,然后应用程序无法检查要注入哪个实现。
因此,您无法在运行时使用依赖注入有条件地注入 bean
相反,您可以使用如下所示的其他设计 -
@Service
public class MyService{
private Wisher wisher;
public Wisher setupWisher(String class){
if (class.equals("A")) {
wisher = new A();
}else if(class.equals("B")){
wisher = new B();
}else if(class.equals("C")){
wisher = new C();
}
}
void myMethod(String requestString) {
int timrHr = new Date().getHours();
setupWisher(requestString).wish(timrHr);
}
}
TA贡献1810条经验 获得超5个赞
String 不是 Spring IoC 框架可管理的 bean,而是类的实例A,B并且C是您的 beans。
你应该做的是声明类A,B并C作为公共接口的实现,并通过这种类型注入相应的 bean:
interface Wisher {
String wish(int timeHr);
}
@Component
public class A implements Wisher {
public String wish(int timeHr){
//some logic of time based wish
return "Hello A"+" good morning";
}
}
@Component
public class B implements Wisher {
public String wish(int timeHr){
//some logic of time based wish
return "Hello B"+" good morning";
}
}
@Component
public class C implements Wisher {
public String wish(int timeHr){
//some logic of time based wish
return "Hello C"+" good morning";
}
}
@Service
public class MyService{
@Autowired
private Wisher a; // instance of "A" or "B", or "C"
void myMethod() {
int timrHr = new Date().getHours();
wisher.wish(timrHr);
}
}
添加回答
举报