泽西2 + HK2 - 自动绑定classess

时间:2016-06-13 15:51:19

标签: java jersey-2.0 hk2

继续主题 Jersey 2 + HK2 - @ApplicationScoped not working

我已经知道,如何绑定类以正确地@Inject

您有什么想法,如何自动化这个过程?将bind语句中的每一项服务放在我的应用程序中似乎非常难闻。

3 个答案:

答案 0 :(得分:4)

使用Google的Guice多年后,我习惯使用Just-In-Time活页夹,允许注入任意类型而无需任何前期配置。

我也发现必须明确地将每个服务绑定为代码异味的想法。我也不会因为需要使用特殊的构建步骤和为populator添加的初始化代码而感到沮丧。

所以我想出了以下JustInTimeResolver实现:

/**
 * Mimic GUICE's ability to satisfy injection points automatically,
 * without needing to explicitly bind every class, and without needing
 * to add an extra build step.
 */
@Service
public class JustInTimeServiceResolver implements JustInTimeInjectionResolver {

    @Inject
    private ServiceLocator serviceLocator;

    @Override
    public boolean justInTimeResolution( Injectee injectee ) {
    final Type requiredType = injectee.getRequiredType();

        if ( injectee.getRequiredQualifiers().isEmpty() && requiredType instanceof Class ) {
            final Class<?> requiredClass = (Class<?>) requiredType;

            // IMPORTANT: check the package name, so we don't accidentally preempt other framework JIT resolvers
            if ( requiredClass.getName().startsWith( "com.fastmodel" )) {
                final List<ActiveDescriptor<?>> descriptors = ServiceLocatorUtilities.addClasses( serviceLocator, requiredClass );

                if ( !descriptors.isEmpty() ) {
                    return true;
                }
            }
        }
        return false;
    }
} 

在我的项目中,我只是在Jersey应用程序配置中将以下内容添加到我的活页夹中:

bind( JustInTimeServiceResolver.class ).to( JustInTimeInjectionResolver.class );

我得到了像Guice那样的自动绑定创建。

答案 1 :(得分:1)

我建议先看一下:Automatic Service Population

基本过程是在类上使用@Service注释,并在构建时使用JSR-269(APT)处理器(Metadata Generator)。这样做会在jar文件中添加一些元数据(通常在META-INF / hk2-locator / default下)。

然后,您可以确保自动获取这些服务,而不是使用从Populator获得的Dynamic Configuration Service来完成所有这些讨厌的绑定。https://github.com/square/retrofit/issues/1140可以在每个ServiceLocator中使用。

伪代码将是这样的:

public void populate(ServiceLocator locator) throws Exception {
    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    Populator populator = dcs.getPopulator();
    populator.populate(new ClasspathDescriptorFileFinder(getClass().getClassLoader()));
}

在上面的代码中,ClasspathDescriptorFileFinder用于搜索类路径以查找元数据。其他策略可以在OSGi等环境中使用。

IMO这是一种更好的添加服务的方式,而不是自己做所有的绑定。

答案 2 :(得分:0)

我有一个解决我的问题的消化,我尝试过提出的解决方案而不是在这里工作。在我的解决方案中,必须使用@MyInjectable注释对每个类进行注释。

1 - 创建注释

@Retention(RUNTIME)
@Target(ElementType.TYPE)
public @interface MyInjectable {
}

2 - 创建一个AbstractBinder实现

public class MyApplicationBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bindFactory(EMFFactory.class).to(EntityManagerFactory.class).in(Singleton.class);
        bindFactory(EMFactory.class).to(EntityManager.class).in(RequestScoped.class);
        bind(Environment.class).to(Environment.class);
        scanAndBind("com.yourpackage.here");
    }

    private void scanAndBind(String packageName) {
        try {
            Class[] classes = getClasses(packageName);
            for (Class<?> klazz:
                 classes) {
                MyInjectable annotation = klazz.getAnnotation(MyInjectable.class);
                if (annotation!= null) {
                    bind(klazz).to(klazz);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Class[] getClasses(String packageName)
            throws ClassNotFoundException, IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }
        ArrayList<Class> classes = new ArrayList<Class>();
        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName));
        }
        return classes.toArray(new Class[classes.size()]);
    }

    private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }

}

3 - 创建ResourceConfig

public class MyApplication extends ResourceConfig {
    @Inject
    public MyApplication(ServiceLocator locator) {
        ServiceLocatorUtilities.enableImmediateScope(locator);
        ....
        register(new MyApplicationBinder());
    }
}

4 - 在web.xml中正确配置

<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>br.com.solutiontrue.ws</param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>your.package.name.MyApplication</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.resource.validation.disable</param-name>
        <param-value>true</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
</servlet>