0

起初,我有一个弹簧应用程序工作正常:

在此处输入图像描述

但是当像这样将 aop config 添加到 aop.xml 时,它会抛出一个非常 lang 的异常。 在此处输入图像描述

这是 AOP.java:

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.animal.Cat;

public class AOP {
    public static void main(String args[]){

        System.out.println("1");
        BeanFactory factory = new ClassPathXmlApplicationContext("aop.xml");
        Cat c1 =(Cat)factory.getBean("cat1");
        System.out.println("2");
        c1.mark();

    }
}

这是 Cat.java:

package com.animal;
public class Cat {
    public void mark(){
        System.out.println("cat is mark");
    }
}

这是 Rat.java:

package com.animal;

public class Rat {
    public void sleep(){
        System.out.println("rat is sleep");
    }

    public void run(){
        System.out.println("rat running");
    }
}

这是 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:aop="http://www.springframework.org/schema/aop"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop.xsd
">


<bean id="cat1" class="com.animal.Cat">
</bean>

<bean id="rat1" class="com.animal.Rat">
</bean>

<aop:config>

    <aop:pointcut id="cat_mark" expression="execution(public void com.animal.Cat.mark())"  />

    <aop:aspect ref="rat1">
        <aop:before method="sleep" pointcut-ref="cat_mark" />
        <aop:after method="run" pointcut-ref="cat_mark" />
    </aop:aspect>

</aop:config>

如您所见,这是一个非常简单的应用程序,我只是想在 cat 标记之前使用 spring AOP 让 rat 做一些动作。

我有从一些教程复制的配置 XML 文件,但我找不到它有什么问题。


是的,我想念aspectjweaver.jar哪个org.springframework.context需要。这是解决方案:

在此处输入图像描述

4

1 回答 1

1

您已经编辑了您的问题,所以我正在编辑我的答案,因为现在我可以重现您的问题。

其实你原来的切入点是正确的。忘记我说的它是错误的,当我第一次看到它时我解析它是错误的。只需将其改回仅使用一个*,请:

execution(* com.animal.Cat.mark(..))

现在我认为你的问题要简单得多,从你之前发布的调用堆栈来看,但为了用不完整的调用堆栈的屏幕截图替换它而被切断。但是我在您的问题历史中找到了它,查看了旧版本:

...
Caused by: java.lang.ClassNotFoundException: org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException

我相信您只是在运行应用程序时忘记在类路径上放置aspectjweaver.jar(或类似的版本名称aspectjweaver-1.8.13)。这样做,它应该会消失。如果我这样做,您的应用程序会打印:

1
Apr 20, 2018 6:04:34 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFORMATION: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@18769467: startup date [Fri Apr 20 18:04:34 ICT 2018]; root of context hierarchy
Apr 20, 2018 6:04:35 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFORMATION: Loading XML bean definitions from class path resource [aop.xml]
2
rat is sleep
cat is mark
rat running
于 2018-04-18T15:50:00.713 回答