继续讨论主题Jersey 2 + HK2 - @ApplicationScoped not working。
我已经知道如何绑定类,以便正确地@Inject
它们。
你有任何想法如何自动化这个过程吗?在我的应用程序中将每个单独的服务放入bind
语句似乎是非常糟糕的做法。
继续讨论主题Jersey 2 + HK2 - @ApplicationScoped not working。
我已经知道如何绑定类,以便正确地@Inject
它们。
你有任何想法如何自动化这个过程吗?在我的应用程序中将每个单独的服务放入bind
语句似乎是非常糟糕的做法。
使用谷歌的Guice已经好几年了,我已经习惯了即时绑定器的可用性,它允许注入任意类型而无需事先配置。
我也认为显式绑定每个服务的想法不太好。 我也不喜欢需要使用特殊的构建步骤以及填充程序的附加初始化代码。
因此,我设计了以下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;
}
}
bind( JustInTimeServiceResolver.class ).to( JustInTimeInjectionResolver.class );
我希望能够像在Guice中一样,自动创建绑定。
我建议您首先查看这里:自动服务填充。
基本过程是在您的类上使用@Service注释,并在构建时使用JSR-269(APT)处理器(元数据生成器)。这样做将向您的jar文件添加一些元数据(通常在META-INF / hk2-locator / default下)。
然后,您可以确保这些服务被自动捕获,而无需执行所有那些繁琐的绑定,方法是使用动态配置服务中提供的填充器,该服务在每个ServiceLocator中都可用。
伪代码如下:
public void populate(ServiceLocator locator) throws Exception {
DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
Populator populator = dcs.getPopulator();
populator.populate(new ClasspathDescriptorFileFinder(getClass().getClassLoader()));
}
@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>