【问题标题】:Interceptor's @AroundInvoke not triggered拦截器的@AroundInvoke 未触发
【发布时间】:2017-09-13 11:36:08
【问题描述】:

我正在研究拦截器在 java 中是如何工作的。我正在使用 Netbeans IDE,刚刚创建了一个名为 Interceptors 的新项目。

我创建了一个名为“logged”的注释

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Logged { }

然后我创建了一个类“LoggedInterceptor”

@Interceptor
public class LoggedInterceptor implements Serializable {

    public LoggedInterceptor() {}

    @AroundInvoke
    public Object logMethodEntry(InvocationContext invocationContext) throws Exception 
    {

        System.out.println("Entering method: "
                + invocationContext.getMethod().getName() + " in class "
                + invocationContext.getMethod().getDeclaringClass().getName());

        return invocationContext.proceed();
    }
}

然后我刚刚创建了一个使用 Logged 注释的类

public class SuperService 
{
    @Logged
    public String deliverService(String uid) 
    {
        return uid;
    }

    public static void main(String[] args) 
    {
        SuperService ss = new SuperService();
        System.out.println(ss.deliverService("sisi"));
    }
}

什么也没发生。后来我在 src/main/resources/META-INF/ 下添加了一个名为 beans.xml 的 xml 文件

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
    version="1.1"
    bean-discovery-mode="all">
    <interceptors>
        <class>ascompany.interceptors.LoggedInterceptor</class>
    </interceptors>
</beans>

但是当我调用deliverService 方法时不会调用logMethodEntry 方法。我是否缺少其他一些配置文件?还是只是别的?

我已经尝试将 @Priority 注释添加到 LoggedInterceptor 但没有任何改变...

编辑:

正如@Luciano van der Veekens 所说,我在 LoggedInterceptor 中添加了 logget 注释,但没有任何改变

【问题讨论】:

    标签: java aop interceptor


    【解决方案1】:

    您忘记使用 @Logged 注释 LoggedInterceptor 类。这实际上将注解绑定到拦截器。

    @Logged
    @Interceptor
    public class LoggedInterceptor implements Serializable {
    }
    

    他们在Java EE 6 教程之一中做了同样的事情。

    而且看起来SuperService 只是一个普通课程。拦截器是一个 Java EE 概念,仅适用于部署在应用服务器上的 EJB。

    【讨论】:

    • 我添加了它...但没有任何改变...还有什么?
    • @MarcoCastano 拦截器仅适用于部署在应用服务器上的 EJB
    • @LucianVanDerVeekens 好的,所以我认为它错了...感谢您的时间...您知道是否可以在以这种方式执行方法之前或之后执行某些操作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2022-09-28
    相关资源
    最近更新 更多