2015-09-04 193 views
3

我正在用java做一些測試例子,我想出了一個使用@AroundInvoke的例子。問題是我不確切知道調用的方法在哪裏。@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()); 
    } 
} 

回答

3

我想通了,做一個ñ其他攔截器的例子。

@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註釋被用於指定爲被管理對象的方法的攔截器的方法。

我希望,這可以幫助別人!