java - How can I select Spring bean instance at runtime -
based on parameters passed method, need select 1 of many spring beans implementations of same class, configured different parameters.
e.g. if user invokes method, need call doofoo()
on bean a, if it's user b need call same method, on bean b.
is there 'springier' way of doing other sticking beans in map, , deriving key parameters passed method?
seems want servicelocator
using application context registry.
see servicelocatorfactorybean support class creating servicelocators mapping keys bean names without coupling client code spring.
other option use naming convention or annotation based configuration.
for example, assuming annotate services @exampleannotation("someid")
, can use following service locator retrieve them.
public class annotationservicelocator implements servicelocator { @autowired private applicationcontext context; private map<string, service> services; public service getservice(string id) { checkservices(); return services.get(id); } private void checkservices() { if (services == null) { services = new hashmap<string, service>(); map<string, object> beans = context.getbeanswithannotation(exampleannotation.class); (object bean : beans.values()) { exampleannotation ann = bean.getclass().getannotation(exampleannotation.class); services.put(ann.value(), (service) bean); } } } }
Comments
Post a Comment