![](/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.