我正在编写一个公开 REST API 的简单微服务。所以我开始使用泽西岛,当然我需要将我的对象注入球衣资源中。基本上,我有2个类来定义一组资源,其中一些需要使用另一个服务。
所以基本上我有:
public interface MyService {
String getServiceName();
void doService();
}
该接口的2种实现(MyServiceBean和My备选ServiceBean)
而且,就我对阅读新泽西文件的理解,我定义了一个hk2活页夹:
public class MyBinder implements Binder{
@Override
public void bind(DynamicConfiguration config) {
DescriptorImpl descriptor = BuilderHelper.link(MyServiceBean.class).named("MyServiceBean").to(MyService.class).build();
config.bind(descriptor);
config.bind(BuilderHelper.link(MyAlternativeServiceBean.class).named("MyAlternativeServiceBean").to(MyService.class).build());
}
我将此活页夹注册到ApplicationConfig类
public class ApplicationConfig extends ResourceConfig{
public ApplicationConfig(){
property("property.value", "MyAlternativeServiceImplementation");
registerInstances(new MyBinder());
}
}
并正确注释到资源中
@Path("first")
public class First {
@Inject @Named(value = "MyServiceBean")
private MyService myService;
//...
}
@Path("second")
public class Second {
@Inject @Named(value = "MyAlternativeServiceBean")
private MyService myService;
//...
}
在MyService实现没有参数构造函数之前,所有操作都有效。但在一种情况下,我还需要为MyAlternativeServiceBean提供一个依赖项。
这是构造函数
@Inject @Named("property.value")
public MyAlternativeServiceBean(String property){
this.property = property;
}
但我有一个例外:
javax.servlet.ServletException: A MultiException has 5 exceptions. They are:|1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=String,parent=MyAlternativeServiceBean,qualifiers={}),position=0,optional=false,self=false,unqualified=null,2080509613)|2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.hpe.services.MyAlternativeServiceBean errors were found|3. java.lang.IllegalStateException: Unable to perform operation: resolve on com.hpe.services.MyAlternativeServiceBean|4. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.hpe.tests.SecondEntryPoint errors were found|5. java.lang.IllegalStateException: Unable to perform operation: resolve on com.hpe.tests.SecondEntryPoint|
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:392)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:219)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:501)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:229)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:427)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:973)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1035)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:641)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:231)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Thread.java:745)
基本上,我不知道如何在hk2中注入属性/常量(例如,我可以从配置文件中读取)
谢谢
问候
您可以做的是创建一个自定义注释
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Config {
String value();
}
然后为它创建一个注射器
(允许使用自定义注释进行注入)
public static class ConfigInjectionResolver implements InjectionResolver<Config> {
private static final Map<String, String> properties = new HashMap<>();
public ConfigInjectionResolver() {
properties.put("greeting.message", "Hello World");
}
@Override
public Object resolve(Injectee injectee, ServiceHandle<?> handle) {
if (String.class == injectee.getRequiredType()) {
AnnotatedElement elem = injectee.getParent();
if (elem instanceof Constructor) {
Constructor ctor = (Constructor) elem;
Config config = (Config) ctor.getParameterAnnotations()[injectee.getPosition()][0];
return properties.get(config.value());
} else {
Config config = elem.getAnnotation(Config.class);
return properties.get(config.value());
}
}
return null;
}
@Override
public boolean isConstructorParameterIndicator() { return true; }
@Override
public boolean isMethodParameterIndicator() { return false; }
}
这个例子只使用了一个< code>Map,但是我相信您可以知道如何使用< code>Properties。注册< code>InjectionResolver后,您现在可以
public SomeService(@Config("some.property") String property) {}
这是一个完整的测试案例
import org.glassfish.hk2.api.Injectee;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.ServiceHandle;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import java.lang.annotation.*;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import static org.junit.Assert.*;
/**
* Run like any other JUnit Test. Only one required dependency
*
* <dependency>
* <groupId>org.glassfish.jersey.test-framework.providers</groupId>
* <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
* <version>${jersey2.version}</version>
* </dependency>
*
* @author Paul Samsotha
*/
public class ConfigExample extends JerseyTest {
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public static @interface Config {
String value();
}
public static class ConfigInjectionResolver implements InjectionResolver<Config> {
private static final Map<String, String> properties = new HashMap<>();
public ConfigInjectionResolver() {
properties.put("greeting.message", "Hello World");
}
@Override
public Object resolve(Injectee injectee, ServiceHandle<?> handle) {
if (String.class == injectee.getRequiredType()) {
AnnotatedElement elem = injectee.getParent();
if (elem instanceof Constructor) {
Constructor ctor = (Constructor) elem;
Config config = (Config) ctor.getParameterAnnotations()[injectee.getPosition()][0];
return properties.get(config.value());
} else {
Config config = elem.getAnnotation(Config.class);
return properties.get(config.value());
}
}
return null;
}
@Override
public boolean isConstructorParameterIndicator() { return true; }
@Override
public boolean isMethodParameterIndicator() { return false; }
}
private static interface GreetingService {
String getGreeting();
}
private static class ConfiguredGreetingService implements GreetingService {
private String message;
public ConfiguredGreetingService(@Config("greeting.message") String message) {
this.message = message;
}
@Override
public String getGreeting() {
return this.message;
}
}
@Path("greeting")
public static class GreetingResource {
@Inject
private GreetingService greetingService;
@GET
public String getConfigProp() {
return greetingService.getGreeting();
}
}
@Override
public ResourceConfig configure() {
ResourceConfig config = new ResourceConfig(GreetingResource.class);
config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
config.register(new AbstractBinder(){
@Override
protected void configure() {
bind(ConfiguredGreetingService.class).to(GreetingService.class).in(Singleton.class);
bind(ConfigInjectionResolver.class)
.to(new TypeLiteral<InjectionResolver<Config>>(){})
.in(Singleton.class);
}
});
return config;
}
@Test
public void should_get_configured_greeting() {
final Response response = target("greeting")
.request().get();
assertEquals("Hello World", response.readEntity(String.class));
}
}
我有一个资源类 我尝试了泽西岛2.0的依赖注入中的答案 如果我使用 启动服务器时,我得到 如果我删除了上述依赖项,那么我得到 资源配置类是 活页夹类是 我在嵌入式模式下使用tomcat并添加init参数 我如何在控制器中注入服务?注入是单元测试的首选方式吗(当服务实现调用另一个服务时,比如说XService ),单元测试不应该依赖于Xservice,因此demoServiceImpl如何从测试中将
我正在尝试设置一个基于jersey 2的REST客户端。该客户端代码需要在Jetty 9服务器(独立,非嵌入式)中运行,并且应该从另一个服务中检索/使用数据。我最基本的第一次测试电话如下: 此调用失败,并出现以下错误: 异常在线程"MyApp"MultiException堆栈1的1State.access:没有对象可用于注入在SystemInject teeImpl(必需类型=ServiceLoc
这是我为我的HTTPServer编写的内容: 任何帮助都将不胜感激。
我目前使用的是球衣 我现在要做的是设置泽西,这样当查询参数进来时(比如缩进),我可以告诉Jackson以“更漂亮的格式,也就是缩进”序列化JSON。您可以通过使用SerializationConfig.Feature.INDENT_OUTPUT配置JSON映射器来轻松地告诉Jackson这样做。 问题是,我如何在每个请求的基础上获取一个queryparam并使用它来修改Jackson的输出?
我试图将资源的实例注入具有Singleton作用域的JAX-RS应用程序,但当我这样做时,我得到: 警告:在服务器运行时中注册的提供程序com.test.jersey.app.MyResource未实现任何适用于服务器运行时的提供程序接口。由于约束配置问题,将忽略提供程序com.test.jersey.app.MyResource。 我有一个如下的应用程序,它需要一个已经运行的MyResource
我很难用泽西岛2(2.7)和泽西岛的内置HK2依赖注入来获得一个非常基本的单例类实现。我正在雄猫上运行这个。 我的目标是创建一个支持类的单例实例,供各种web服务方法使用。在构造函数注入、方法注入和注释类成员之间,我没有强烈的偏好(如下所述)。 这是我的单身班: 这是我的应用程序类: 以下是我的Provider/ContextResolver类: web.xml: 我打算在其中注入 JustOne