在这个项目中: https://github.com/jstemen/json-to-db
我已经能够通过以下方式将Jersey 2链接到Spring数据:
public class MyApplication extends ResourceConfig {
/**
* Register JAX-RS application components.
*/
@Inject
public MyApplication(ServiceLocator serviceLocator) {
//ToDo: find a way to have Jersey better interface with Spring
//Pull bean out of Spring
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
Rest rest = ctx.getBean(Rest.class);
//Link pulled out Spring bean Jersey's DI framework
DynamicConfiguration dc = Injections.getConfiguration(serviceLocator);
Injections.addBinding(
Injections.newBinder(rest)
.to(Rest.class),
dc);
dc.commit();//Don't forget to commit
register(Rest.class); //Mark Rest class as an REST endpoint to Jersey
}
}
然而,它并不是很有说服力。无论如何我可以让我的Web.xml加载Jersey 2和Spring并将Spring bean自动映射到Jersey REST端点吗?如果有人分支我的回购并分享它以证明如何做得更好,那将是非常棒的!
答案 0 :(得分:0)
Jersey 2附带了与Spring集成的扩展,请参阅https://jersey.java.net/documentation/latest/spring.html
这很好用,我们的Spring组件通过字段注入直接自动连接到我们的资源中,如下所示:
@Component
@Path("/")
public class FooResource {
@Autowired
private SomeComponent someComponent;
protected FooResource() {}
@GET
public String bar() {
return "foobar";
}
}
在您的ResourceConfig
扩展课程中,您只需执行register(FooResource.class)
!有关详细信息,请参阅文档和Spring DI example。