Jeśli moja strona Ci pomogła, i chcesz aby była bardziej rozwijana, wesprzyj mnie
buy me a coffee
|
1. Interceptor to programowanie aspektowe w Java EE.
Mamy możliwość wykonania czynności przed lub po wywołaniu metody.
Zobaczmy na przykład.
Najpierw musimy zdefiniować kwalifikator (Qualifier) intercepotor-a.
package pl.edu.java.cdi.managedBeans;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
import javax.interceptor.InterceptorBinding;
@Qualifier
@InterceptorBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Log {}
package pl.edu.java.cdi.managedBeans;
import java.io.Serializable;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import org.jboss.logging.Logger;
@Interceptor
@Log
public class LogInterceptor implements Serializable {
private static final Logger LOGGER =
Logger.getLogger(LogInterceptor.class);
@AroundInvoke
public Object logMethodEntry(InvocationContext ic) throws Exception {
LOGGER.info("Wywolana zostala metoda: " + ic.getMethod().getName());
return ic.proceed();
}
}
package pl.edu.java.cdi.managedBeans;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
@Named
@RequestScoped
public class MojController {
@Log
public String getLog() {
return "Metoda loggowana";
}
}
i należy do pliku beans.xml dodać:
<interceptors>
<class>pl.edu.java.cdi.managedBeans.LogInterceptor</class>
</interceptors>
|