【发布时间】:2018-02-28 08:54:02
【问题描述】:
我想为我当前的 Stack 创建一个 LoggingInterceptor:
- Tomcat 8.5.24
- 焊接 2.4.5-Final
- JSF 2.3.3
这是标记方法或类型以进行拦截的Annotation。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.enterprise.util.Nonbinding;
import javax.interceptor.InterceptorBinding;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@InterceptorBinding
public @interface Logging {
@Nonbinding
Level value() default Level.TRACE;
public enum Level {
NONE, ALL, TRACE, DEBUG, INFO, WARN, ERROR;
}
}
拦截器逻辑如下:
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
@Interceptor
@Logging
public class LoggingInterceptor {
@AroundInvoke
public Object interceptBusiness(final InvocationContext invocationContext) throws Exception {
Logger log = LoggerFactory.getLogger(invocationContext.getMethod().getDeclaringClass().getName());
log.trace("LOG start of method");
Object result = invocationContext.proceed();
log.trace("LOG end of method");
return result;
}
}
一个简化的 Bean:
import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.inject.Inject;
import javax.faces.view.ViewScoped;
@Named
@ViewScoped
@Logging(Level.DEBUG)
public class ListController implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
EntityService entityService;
private List<Entity> entityList;
public List<Entity> getEntityList() {
return this.entityList;
}
public void setEntityList(final List<Entity> entityList) {
this.entityList= entityList;
}
public String doSomething(){
List<Entity> entityList = new ArrayList<>();
this.setEntityList(entityList);
return "";
}
@PostConstruct
public void setUp() {
this.setEntityList(this.entityService.findAll());
}
}
如果在运行时调用我的业务方法拦截器,例如在调用 doSomething() 方法的 jsf 视图中按下按钮时,它的作用就像一个魅力。 doSomething() 和 setEntityList() 方法都将被记录。
但是在@PostConstruct 方法中调用的所有方法根本不会被记录。这意味着在@PostConstruct 方法中调用时不会记录setEntityList() 方法。
我可以做些什么来记录从@PostConstruct 方法调用的方法。我会很感激一些帮助。提前致谢。
因 HRgiger 的回答而更新:
我还在拦截器逻辑中尝试了@PostConstruct 方法,但使用此方法我只能记录@PostConstruct 本身的调用,但不会记录@PostConstruct 方法中调用的方法,这仍然是我的主要方法问题。
@PostConstruct
public void interceptLifecycle(final InvocationContext invocationContext) throws Exception {
Logger log = LoggerFactory.getLogger(invocationContext.getTarget().getClass().getSimpleName());
log.info("LOG start of POSTCONSTRUCT");
invocationContext.proceed();
log.info("LOG end of POSTCONSTRUCT");
}
【问题讨论】:
标签: java jakarta-ee cdi interceptor weld