// Create and register resources
final ResourceConfig resourceConfig = new ApiServiceConfig()
.register(new DependencyInjectionBinder());
ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
contextHandler.setContextPath("/mydomain/api");
Server jettyServer = new Server(8585);
jettyServer.setHandler(contextHandler);
ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(resourceConfig));
contextHandler.addServlet(jerseyServlet, "/*");
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jettyServer.destroy();
}
public class ApiServiceConfig extends ResourceConfig {
public ApiServiceConfig() {
for(JsonNode jsonNode: nodeArray) {
// JSON endpoint service description example.
//{
// "service": "/item/{id}",
// "method": "GET",
// "process": {
// "@type": "com.mycompany.projectx.endpoint.services.GetController",
// "uri_param": "id",
// "type": "item",
// "fields": "uuid,name,content_area,title,grade,dok,bloom,item_banks,...,item_banks_titles"
// }
//}
// Json property "service" describes a URL pattern for a request (eg. "/item/{id}").
final String path = jsonNode.get("service").asText();
// Api RESTful verb ('GET', 'POST', etc.)
final String method = jsonNode.get("method").asText();
// Map a process description of a service to specific controller implementation class.
// This is the instance creation where I want injection to happen.
IController controller = this.objectMapper.convertValue(jsonNode.get("process"), AbstractBaseController.class);
// Controller is added to a HashMap
...
final Resource.Builder resourceBuilder = Resource.builder();
resourceBuilder.path(path);
final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod(method);
methodBuilder.produces(new MediaType("text", "plain"))
handledBy((Inflector)(ctx) -> {
// Controller is retrieved from the HashMap
controller.execute(new ProcessEvent());
...
return responseResult;
});
final Resource resource = resourceBuilder.build();
registerResources(resource);
}
}
}
public class GetController extends AbstractBaseController {
@Config("data.cassandra")
String connectionString; // == null, but should be a string injected.
public GetController() {
}
@Override
public ProcessEvent process(ProcessEvent event) throws Exception {
String uri_param = this.uri_param;
event.contentType = "application/json";
event.object = ".Get method of Item endpoint got executed. Cassandra IP: " + getApplicationProperties().getProperty("data.cassandra");
return event;
}
依赖关系解析器绑定器注册在DependencyInjectionBinder
类中:
public class DependencyInjectionBinder extends AbstractBinder {
@Override
protected void configure() {
bind(ConfigInjectionResolver.class)
.to(new TypeLiteral<InjectionResolver<Config>>() {})
.in(Singleton.class);
}
}
ConfigInjectionResolver实现InjectionResolver并解析某些逻辑。
apiserviceConfig
在循环中遍历描述并创建endpoint。为每个endpoint创建、填充资源生成器并注册资源。在endpoint资源的创建过程中,在Jackson-DataBind的帮助下实例化了一个类:
IController controller = this.objectMapper.convertValue(jsonNode.get("process"), AbstractBaseController.class);
resourceConfig.register(AnEndpointClass.class);
要显式注入对象,您需要获取ServiceLocator
,并调用locator.inject(controller)
。您可以在特性
中获得ServiceLocator
。
由于还需要使用控制器注册资源,因此还需要在特性
中注册资源的方法。为此,可以使用ModelProcessor
。您可以在泽西文档中阅读更多关于它的信息。它允许您更改Jersey的资源模型。在这里,我们可以注册我们以编程方式构建的所有资源。
下面是一个使用Jersey测试框架的完整示例。您可以像运行任何其他JUnit测试一样运行它。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.logging.Logger;
import javax.annotation.Priority;
import javax.inject.Singleton;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.core.Response;
import org.glassfish.hk2.api.Injectee;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.ServiceHandle;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.ServiceLocatorProvider;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.process.Inflector;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.model.ModelProcessor;
import org.glassfish.jersey.server.model.Resource;
import org.glassfish.jersey.server.model.ResourceMethod;
import org.glassfish.jersey.server.model.ResourceModel;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Stack Overflow https://stackoverflow.com/q/36410420/2587435
*
* Run this like any other JUnit test. Only one required dependency
*
* <dependency>
* <groupId>org.glassfish.jersey.test-framework.providers</groupId>
* <artifactId>jersey-test-framework-provider-inmemory</artifactId>
* <version>${jersey2.version}</version>
* <scope>test</scope>
* </dependency>
*
* @author Paul Samsotha
*/
public class PropsInjectionTest extends JerseyTest {
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public static @interface Config {
String value();
}
@Singleton
public static class ConfigInjectionResolver implements InjectionResolver<Config> {
@Override
public Object resolve(Injectee injectee, ServiceHandle<?> root) {
if (String.class == injectee.getRequiredType()) {
Config anno = injectee.getParent().getAnnotation(Config.class);
if (anno != null) {
String key = anno.value();
return key + "Value";
}
}
return null;
}
@Override
public boolean isConstructorParameterIndicator() { return false; }
@Override
public boolean isMethodParameterIndicator() { return false; }
}
public static class Controller {
@Config("Key")
private String prop;
public String getProp() {
return prop;
}
}
public static class ResourceFeature implements Feature {
@Override
public boolean configure(FeatureContext ctx) {
final ServiceLocator locator = ServiceLocatorProvider.getServiceLocator(ctx);
final Controller controller = new Controller();
locator.inject(controller);
final Resource.Builder builder = Resource.builder().path("test");
final ResourceMethod.Builder methodBuilder = builder.addMethod("GET");
methodBuilder.handledBy(new Inflector<ContainerRequestContext, String>(){
@Override
public String apply(ContainerRequestContext data) {
return controller.getProp();
}
});
final Resource resource = builder.build();
ctx.register(new MyModelProcessor(resource));
return true;
}
@Priority(100)
static class MyModelProcessor implements ModelProcessor {
private final Resource[] resources;
public MyModelProcessor(Resource... resources) {
this.resources = resources;
}
@Override
public ResourceModel processResourceModel(ResourceModel rm, Configuration c) {
final ResourceModel.Builder builder = new ResourceModel.Builder(false);
// add any other resources not added in this feature. If there are none,
// you can skip this loop
for (Resource resource: rm.getResources()) {
builder.addResource(resource);
}
for (Resource resource: this.resources) {
builder.addResource(resource);
}
return builder.build();
}
@Override
public ResourceModel processSubResource(ResourceModel rm, Configuration c) {
return rm;
}
}
}
@Override
public ResourceConfig configure() {
return new ResourceConfig()
.register(new ResourceFeature())
.register(new LoggingFilter(Logger.getAnonymousLogger(), true))
.register(new AbstractBinder() {
@Override
protected void configure() {
bind(ConfigInjectionResolver.class)
.to(new TypeLiteral<InjectionResolver<Config>>(){})
.in(Singleton.class);
}
});
}
@Test
public void allShouldBeGood() {
final Response response = target("test").request().get();
assertThat(response.readEntity(String.class), is("KeyValue"));
}
}
问题内容: 我最近升级了一个项目以使用hibernate3.6.10.Final。该项目使用常春藤检索和依赖项。现在,我收到一个错误,即找不到slf4j中的方法。我相信这是由于hibernate- core(要求1.6.1)和hibernate-commons- annotations(要求1.5.8)之间的slf4j依赖项冲突造成的。根据hibernate-core ivy.xml,hibern
故事:我使用JDK8和IVY作为ANT Builder的依赖项管理器。一切都很好。我的类能够找到依赖关系。 问题:现在我要打开JDK11,现在找不到依赖关系。 我需要的解决方案是:我需要OpenJDK11的常春藤依赖项来支持
问题内容: 假设我有四个项目: 项目A(依赖于B和D) 项目B(依赖于D) 项目C(依赖于D) 项目D 在这种情况下,如果我运行项目A,则Maven将正确地解决对D的依赖关系。如果我理解正确,则Maven始终以最短的路径获取依赖关系。由于D是A的直接依赖项,因此将使用B内指定的D而不是D。 但是现在假设这种结构: 项目A(依赖于B和C) 项目B(依赖于D) 项目C(依赖于D) 项目D 在这种情况下
我已经在pom中配置了本地maven存储库。xml。当我构建项目时,它会显示依赖项下载错误(请参阅下面的日志)。Maven正在尝试从我的本地Maven存储库下载所有依赖项。 日志 这是我的pom。xml文件 本地存储库是http://XXX。XXX。XX。XXX:8081/artifactory/libs本地发布 xml。背景
在正式开始编译最终系统之前,我们需要静下心来认真分析一下这个最终系统究竟需要哪些东西。 所谓"依赖性"是多方面的。一般来说,可以分为"运行时依赖"、"编译安装依赖"、"测试依赖"三个层面。为了构建一个严谨的自依赖系统,显然这三种依赖性都必须满足。运行时依赖比较简单,一般就是库的依赖;而后两种依赖则比较复杂(运行时依赖实际上取决于编译安装依赖)。比如,如果你不需要安装文档,那么 Textinfo 就
我试图构建一个具有spark依赖关系的非常基本的scala脚本。但我不能用它做罐子。 我的scala源代码在: /exampleapp/main/scala/example/hello.scala 项目名为exampleapp。