【问题标题】:Where is @AroundInvoke interceptor invoked?@AroundInvoke 拦截器在哪里调用?
【发布时间】:2015-09-04 16:15:07
【问题描述】:

我正在用 java 做一些测试示例,我想出了一个使用 @AroundInvoke 的示例。问题是我不知道调用的方法到底在哪里。

这个测试在它调用 post() 方法的地方进行了调用,但我真的不知道它是如何工作的 (Using Interceptors explanation)。

@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));
}

调用顺序是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));
        }
    }
}

MonitorSink

@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class MonitorSink {

    @Inject
    LogSink LOG;

    public void onCallEvent(@Observes CallEvent event){
        LOG.log(event.toString());
    }
}

【问题讨论】:

    标签: jakarta-ee interceptor


    【解决方案1】:

    通过另一个拦截器示例,我想通了。

    @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;
        }
    
    }
    

    @AroundInvoke 注解用于为托管对象方法指定拦截器方法。

    我希望,这可以帮助别人!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多