I am learning Interceptor Binding using annotations. The version is Java 11, and Jakarta EJB 4. The server is GlassFish 7. There is no deployment descriptor and annotations archive all requirements.
I have added a print statement to see whether it’s working. But, there is no output in the server log. Here is the code.
Auth.java
package com.aadhil.ejb.annotation;
import java.lang.annotation.*;
import jakarta.interceptor.InterceptorBinding;
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface Auth {
}
AuthInterceptor.java
package com.aadhil.ejb.interceptor;
import com.aadhil.ejb.annotation.Auth;
import jakarta.interceptor.AroundInvoke;
import jakarta.interceptor.Interceptor;
import jakarta.interceptor.InvocationContext;
@Auth
@Interceptor
public class AuthInterceptor {
@AroundInvoke
public Object authenticate(InvocationContext invocationContext) throws Exception {
System.out.println("Auth Interceptor");
return invocationContext.proceed();
}
}
LoginImpl.java
package com.aadhil.ejb.impl;
import com.aadhil.ejb.annotation.Auth;
import com.aadhil.ejb.entity.User;
import com.aadhil.ejb.remote.Login;
import jakarta.ejb.Stateless;
import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.PersistenceContext;
@Auth
@Stateless
public class LoginImpl implements Login {
@PersistenceContext(unitName = "WebPU")
private EntityManager em;
@Override
public User login(String email, String password) {
try {
return em.createQuery("SELECT u FROM User u WHERE u.username=:username AND u.password=:password", User.class)
.setParameter("username", email)
.setParameter("password", password)
.getSingleResult();
} catch (NoResultException ex) {
return null;
}
}
}
When using @Interceptors
annotation in the session bean class and @AroundInvoke
annotation in the interceptor class, it worked fine. But, when trying with a custom annotation class with @InterceptorBinding
annotation, I cannot see any log. I also added the @Inherited
annotation to my custom annotation. But I got the same result. My tutor does not use the @Inherited
annotation or any XML file to configure the interceptors.