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);
}
}
添加回答
舉報