我已成功实现了目标PARAMETER
的自定义注入注释。我不明白我是如何制作注释支持目标METHOD
的呢?
以下是我的示例代码:
Hello注释:
@Retention(RUNTIME)
@Target({METHOD, PARAMETER})
public @interface Hello {
}
Hello注释解析器:
@Singleton
public class HelloResolver {
public static class HelloInjectionResolver extends ParamInjectionResolver<Hello> {
public HelloInjectionResolver() {
super(HelloValueFactoryProvider.class);
}
}
@Singleton
public static class HelloValueFactoryProvider extends AbstractValueFactoryProvider {
@Inject
public HelloValueFactoryProvider(final MultivaluedParameterExtractorProvider extractorProvider,
final ServiceLocator injector) {
super(extractorProvider, injector, UNKNOWN);
}
@Override
protected Factory<?> createValueFactory(final Parameter parameter) {
if (!String.class.equals(parameter.getRawType())) return null;
if (parameter.getAnnotation(Hello.class) == null) return null;
return new AbstractContainerRequestValueFactory<String>() {
@Override
public String provide() {
final DateTime now = DateTime.now();
if (22 < now.getHourOfDay() || now.getHourOfDay() < 6) {
throw new WebApplicationException(FORBIDDEN);
} else {
return format("Hello, it is %s o'clock so I am awake! :)", forPattern("HH:mm").print(now));
}
}
};
}
}
public static class Binder extends AbstractBinder {
@Override
protected void configure() {
bind(HelloValueFactoryProvider.class).to(ValueFactoryProvider.class).in(Singleton.class);
bind(HelloInjectionResolver.class).to(
new TypeLiteral<InjectionResolver<Hello>>() {
}
).in(Singleton.class);
}
}
}
Hello资源:
@Path("hello")
public class HelloResource {
@GET
@Path("method")
@Produces(APPLICATION_JSON)
@Hello
public String method() {
return "Hello!";
}
@GET
@Path("param")
@Produces(APPLICATION_JSON)
public String param(@Hello final String hello) {
return hello;
}
}
当我点击
http://localhost:8080/hello/method
我得到你好!如果小时在禁止的时间间隔内,则返回。
答案 0 :(得分:-1)
我不确定这会有效,但你可以试试这个:
public static class HelloInjectionResolver extends ParamInjectionResolver<Hello> {
public HelloInjectionResolver() {
super(HelloValueFactoryProvider.class);
}
public boolean isMethodParameterIndicator() {
return true;
}
}
警告:我自己没有尝试过,但理论上应该允许你的解析器作为方法中的参数。