Java Spring AOP xml配置不支持';行不通
我试图编写一个简单的AOP程序,并对xml文件进行如下配置。但是当我运行程序时,结果似乎不是调用通知,而是只执行非通知部分 下面是方法类:Java Spring AOP xml配置不支持';行不通,java,xml,spring,namespaces,aop,Java,Xml,Spring,Namespaces,Aop,我试图编写一个简单的AOP程序,并对xml文件进行如下配置。但是当我运行程序时,结果似乎不是调用通知,而是只执行非通知部分 下面是方法类: public class MessageWriterStdOut { public void writeMessage() { System.out.print("World"); } } 这是bean类: public class MyBeanOfHelloWorld { private MessageWriterS
public class MessageWriterStdOut {
public void writeMessage() {
System.out.print("World");
}
}
这是bean类:
public class MyBeanOfHelloWorld {
private MessageWriterStdOut messageWriterStdOut;
public void execute() {
messageWriterStdOut.writeMessage();
}
public void setMessageWriterStdOut(MessageWriterStdOut messageWriterStdOut) {
this.messageWriterStdOut = messageWriterStdOut;
}
}
建议课是这样的:
public class MessageDecorator implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.print("Hello ");
Object retVal = invocation.proceed();
System.out.println("!");
return retVal;
}
}
主要方法是:
public class HelloWorldAopExample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("/META-INF/spring/context-aop.xml");
ctx.refresh();
MyBeanOfHelloWorld myBeanOfHelloWorld = (MyBeanOfHelloWorld) ctx.getBean("myBeanOfHelloWorld");
myBeanOfHelloWorld.execute();
}
}
xml配置为:
<aop:config>
<aop:pointcut id="helloExecution"
expression="execution(* com..playground..writeMessage*()) and args(invocation)" />
<aop:aspect ref="advice">
<aop:around pointcut-ref="helloExecution" method="invoke" />
</aop:aspect>
</aop:config>
<bean id="advice" class="com..playground.aophelloworld.MessageDecorator" />
<bean id="messageWriterStdOut"
class="com..playground.aophelloworld.MessageWriterStdOut" />
<bean id="myBeanOfHelloWorld" class="com..playground.aophelloworld.MyBeanOfHelloWorld">
<property name="messageWriterStdOut" ref="messageWriterStdOut" />
</bean>
但是结果仍然是“world”,而在xml配置中预期的结果是“helloworld!”,为什么有些包路径有两个点?例如:
<aop:pointcut id="helloExecution"
expression="execution(* com..playground..writeMessage*()) and args(invocation)" />
应该是:
<aop:pointcut id="helloExecution"
expression="execution(* com.playground.writeMessage*()) and args(invocation)" />
以及其他一些地方:
<bean id="advice" class="com.playground.aophelloworld.MessageDecorator" />
<bean id="myBeanOfHelloWorld" class="com.playground.aophelloworld.MyBeanOfHelloWorld">
<property name="messageWriterStdOut" ref="messageWriterStdOut" />
更新:
你能试试这个吗
<aop:pointcut id="helloExecution"
expression="execution(* com..playground.MessageWriterStdOut.writeMessage(..))" />
参数(调用)应该做什么?因为当我没有添加此参数时,它总是显示错误:“切入点格式不正确:错误在::0中正式解除绑定”。所以我添加了这个args,它是advice类中方法的arg。(实际上它不需要基于教程…)我删除了类路径的一些部分,因为它显示起来有点长,所以我在这里使用“.”作为缩写。但这里的“Playerd..writeMessage*()”是因为我在教程设置中看到了这样的设置,当我删除其中一个点时,它会显示语法错误。似乎如果我删除“args(invocation)”,它将始终显示错误信息,如“切入点格式错误:错误在::0中正式解除绑定”。