简体   繁体   中英

Is it possible to dynamically manage @Named injection name from a property file for HK2

We have a core Java application and different plugins for different clients. We are using Hk2 for dependency injection.

I would like to now is it possible to have a way of putting some @Named Qualifier names to properties files of plugins so I can just change the value of the property file to inject different class implementations for different clients.

What I mean is having @Named(key="plugins.impl.xplugin") rather than @Named("XPlugin").

This would help a lot to get rid of so much boilerplate code for plugins.

This is a possible solution for you using IterableProvider (which has a "named" method on it to choose a specific named version at runtime):

@Service
public class Example {
    
    @Inject
    private IterableProvider<MyService> myService;
    
    public MyService getSpecificService(String serviceName) {
        return myService.named(serviceName).get();
    }

    @Contract
    public interface MyService {}
    
    @Service @Named("Foo")
    public static class MyServiceFoo implements MyService {}
    
    @Service @Named("Bar")
    public static class MyServiceBar implements MyService {}

}

In the example above you just pass the name of the service you want ("Foo" or "Bar") to getSpecificService and it will pass back the implementation of your choice.

Note real code would probably want to be more sophisticated about what happens if there is no implementation of the given name for the given service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM