
[英]Unmarshalling XML or JSON to guice injected object in jersey using @InjectParam annotation
[英]@BeanParam annotation in GUICE + JERSEY Bridge
@GET
@Path("/book")
public Response getBook(@BeanParam Filter filter) {
}
过滤器参数正在初始化,但Bean中未设置任何内容
class Filter {@QueryParam("author")String author}
我确实有Filter对象中存在的所有属性的setter和getter。
仅供参考,我正在使用HK2 guice-bridge 。
我能够用guice-bridge重现该问题。 似乎在初始化桥时(通过guiceBridge.bridgeGuiceInjector(...)),仅调用BeanParam的默认构造函数,而不是还设置属性(或使用参数调用构造函数)。
如果在项目中可行,则可以尝试为构造函数提供参数。
这是一个简单的应用程序:
public class App extends ResourceConfig {
@Inject
public App(final ServiceLocator serviceLocator) {
register(Service.class);
final Injector injector = initializeInjector(serviceLocator);
}
private Injector initializeInjector(final ServiceLocator serviceLocator) {
GuiceBridge.getGuiceBridge()
.initializeGuiceBridge(serviceLocator);
final Injector injector = Guice.createInjector(
new ApplicationModule(serviceLocator));
final GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
guiceBridge.bridgeGuiceInjector(injector);
return injector;
}
}
使用的服务:
@Path("service")
public class Service {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response save(@Valid @BeanParam final SimpleBean bean) {
System.out.println(bean.getProperty());
return Response.status(Status.CREATED)
.build();
}
}
这是一个简单的bean:
public class SimpleBean {
// Avoid this constructor!
// public SimpleBean() {
// System.out.println("constructor called");
// }
public SimpleBean(@FormParam("property") final String property) {
this.property = property;
System.out.println("constructor with params called: " + property);
}
@Length(max = 100)
@NotBlank
private String property;
public String getProperty() {
System.out.println("getter called");
return property;
}
public void setProperty(final String property) {
System.out.println("setter called with " + property);
this.property = property;
}
}
使用Guice版本4.1.0,guice-bridge版本2.4.0,Jersey版本2.25.1和Javax Servlet版本3.1.0。
您可以尝试使用没有桥的Guice-Jersey。 有一个名为“ Guice Web服务器模块”的项目,该项目将实现该方法的Guice与Jersey 2,Jetty和Jackson集成在一起。
您需要做的是在Guice上下文中绑定资源,例如
public class MyModule extends AbstractModule() {
public void configure() {
bind(BooksResource.class);
}
有一个Jersey的功能,该功能将扫描所有带@Path注释的绑定,并在实例化后将实例注册到Jersey的上下文中:
public boolean configure(FeatureContext context) {
injector.getBindings().entrySet()
.stream()
.filter(entry -> entry.getKey().getTypeLiteral().getRawType().getAnnotation(Path.class) != null)
.map(entry -> injector.getInstance(entry.getKey()))
.forEach(context::register);
return true;
}
BeanParams还有一个示例(作为集成测试的一部分编写) -BeanParamsIntegrationTest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.