下面是方面java代码:
public class ParamAspect {
public void beforeMethodExecution(String name){
System.out.println("Name: " + name);
}
public void beforeMethodExecution(Employee employee){
System.out.println("Employee Name: " + employee.getName());
}
}
下面是 context.xml 文件:
<aop:config>
<aop:pointcut id="empName" expression="execution(void com.model.Employee.setName(String)) and args(name1)"/>
<aop:pointcut id="empl" expression="execution(void com.model.Employee.setEmployee(com.model.Employee)) and args(empl)"/>
<aop:aspect ref="aspect">
<aop:before pointcut-ref="empName" method="beforeMethodExecution" arg-names="name1"/>
<aop:before pointcut-ref="empl" method="beforeMethodExecution" arg-names="empl"/>
</aop:aspect>
</aop:config>
执行此操作时遇到的错误是:
Caused by: java.lang.IllegalArgumentException: Cannot resolve method 'beforeMethodExecution' to a unique method. Attempted to resolve to overloaded method with the least number of parameters, but there were 2 candidates.
at org.springframework.beans.BeanUtils.findMethodWithMinimalParameters(BeanUtils.java:290)
at org.springframework.beans.BeanUtils.findMethodWithMinimalParameters(BeanUtils.java:231)
at org.springframework.beans.BeanUtils.resolveSignature(BeanUtils.java:332)
at org.springframework.aop.config.MethodLocatingFactoryBean.setBeanFactory(MethodLocatingFactoryBean.java:72)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1475)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1443)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 38 more
但是,如果我更改方面的方法名称
`public void beforeMethodExecution(Employee employee){`
至
`public void beforeMethodExec(Employee employee){`
并在 context.xml 中进行相同的更改
<aop:before pointcut-ref="empl" method="beforeMethodExecution" arg-names="empl"/>
至
<aop:before pointcut-ref="empl" method="beforeMethodExec" arg-names="empl"/>
然后代码就可以正常工作了。
请告诉我为什么同名方法会抛出异常。
最佳答案
尝试使用:
<aop:config>
<aop:pointcut id="empName" expression="execution(void com.model.Employee.setName(String)) and args(name1)"/>
<aop:pointcut id="empl" expression="execution(void com.model.Employee.setEmployee(com.model.Employee)) and args(empl)"/>
<aop:aspect ref="aspect">
<aop:before pointcut-ref="empName" method="beforeMethodExecution(String)"/>
<aop:before pointcut-ref="empl" method="beforeMethodExecution(com.model.Employee)"/>
</aop:aspect>
</aop:config>
关于java - Spring AOP :Cannot resolve method to a unique method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24065975/