![](/img/trans.png)
[英]How to inject prototype bean in Spring AuthenticationSuccessHandler implementation
[英]Spring: How to get bean implementation dynamically?
假設我們有接口:
public interface IAuthentication { }
和兩個實現:
public class LdapAuthentication implements IAuthentication {}
public class DbAuthentication implements IAuthentication {}
最后,我們有一個負責處理身份驗證的bean。 該bean應該使用上面顯示的一種實現(基於db中指定的配置)。
@Service
public class AuthenticationService {
public boolean authenticate(...) {
boolean useDb = ...; //got from db
//my problem here
//how to get right implementation: either LdapAuthentication or DbAuthentication?
IAuthentication auth = ...;
return auth.authenticate(...);
}
}
題:
如何獲得正確的實施?
如果參數值不變:
@Service
public class AuthenticationService {
private IAuthentication auth;
@PostConstruct
protected void init() {
boolean useDb = ...; //got from db
this.auth = ...; //choose correct one
}
public boolean authenticate(...) {
return auth.authenticate(...);
}
}
如果參數是動態的
@Service
public class AuthenticationService {
@Autowired
private ApplicationContext сontext;
public boolean authenticate(...) {
boolean useDb = ...; //got from db
IAuthentication auth = context.getBean(useDb ? DbAuthentication.class : LdapAuthentication.class);
return auth.authenticate(...);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.