Joe*_*Joe 6 java-ee interceptor
我正在用Java做一些测试示例,并且我想出了一个使用@AroundInvoke的示例。问题是我不确切知道该方法在哪里调用。
该测试在调用post()方法的地方进行了调用,但是我真的不知道它是如何工作的(使用Interceptors解释)。
@Test
public void crudtest() {
JsonObjectBuilder todoBuilder = Json.createObjectBuilder();
JsonObject todoToCreate = todoBuilder.
add("caption", "implement").
add("priority", 10).
build();
//The next post execute, invoke the method
Response postResponse = this.provider.target().request().
post(Entity.json(todoToCreate));
}
Run Code Online (Sandbox Code Playgroud)
调用的顺序是BoundaryLogger,然后是MonitorSink
BoundaryLogger.java
...
public class BoundaryLogger {
@Inject
Event<CallEvent> monitoring;
@AroundInvoke
public Object logCall(InvocationContext ic) throws Exception {
long start = System.currentTimeMillis();
try {
return ic.proceed();
} finally {
long duration = System.currentTimeMillis() - start;
monitoring.fire(new CallEvent(ic.getMethod().getName(), duration));
}
}
}
Run Code Online (Sandbox Code Playgroud)
显示器水槽
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class MonitorSink {
@Inject
LogSink LOG;
public void onCallEvent(@Observes CallEvent event){
LOG.log(event.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
我通过做另一个拦截器示例来弄清楚。
@AroundInvoke只是定义一个拦截器,它将由具有@Interceptor(name_class.class)的类调用。
就我而言,这是我所缺少的代码。
ToDoManager.java
@Stateless
@Interceptors(BoundaryLogger.class)
public class ToDoManager {
@PersistenceContext
EntityManager em;
public ToDo findById(long id) {
return this.em.find(ToDo.class,id);
}
public void delete(long id) {
try {
ToDo reference = this.em.getReference(ToDo.class, id);
this.em.remove(reference);
} catch (EntityNotFoundException e) {
//we want to remove it...
}
}
public List<ToDo> all() {
return this.em.createNamedQuery(ToDo.findAll, ToDo.class).getResultList();
}
public ToDo save(ToDo todo) {
return this.em.merge(todo);
}
public ToDo updateStatus(long id, boolean done) {
ToDo todo = this.findById(id);
if(todo == null){
return null;
}
todo.setDone(done);
return todo;
}
}
Run Code Online (Sandbox Code Playgroud)
@AroundInvoke批注用于为托管对象方法指定拦截器方法。
我希望这可以帮助其他人!
| 归档时间: |
|
| 查看次数: |
3267 次 |
| 最近记录: |