Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: How to get bean implementation dynamically?

Tags:

java

spring

Let's say we have interface:

public interface IAuthentication { }

and two implementations:

public class LdapAuthentication implements IAuthentication {}

public class DbAuthentication implements IAuthentication {}

And finally we have a bean that is responsible for processing authentication. This bean should use one of the implementations shown above (based on configuration specified in for example 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(...);
    }
}

Question:
How to get the right implementation?

like image 586
Hubert Avatar asked Sep 03 '25 04:09

Hubert


1 Answers

If parameter value does not change:

@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(...);
    }
}

If parameter is dynamic

@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(...);
    }
}
like image 196
AdamSkywalker Avatar answered Sep 05 '25 00:09

AdamSkywalker