Spring:如何动态获取 bean 实现?

Hub*_*ert 2 java spring

假设我们有接口:

public interface IAuthentication { }
Run Code Online (Sandbox Code Playgroud)

和两个实现:

public class LdapAuthentication implements IAuthentication {}

public class DbAuthentication implements IAuthentication {}
Run Code Online (Sandbox Code Playgroud)

最后,我们有一个负责处理身份验证的 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(...);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:
如何获得正确的实施?

Ada*_*ker 5

如果参数值不变:

@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(...);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果参数是动态的

@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(...);
    }
}
Run Code Online (Sandbox Code Playgroud)