我正在尝试使用 AOP 在带注释的 Controller 之后进行一些处理。一切都在运行,没有错误,但建议没有被执行。
这是 Controller 代码:
@Controller
public class HomeController {
@RequestMapping("/home.fo")
public String home(ModelMap model) {
model = new ModelMap();
return "home";
}
}
以及应用程序配置中的设置
<aop:aspectj-autoproxy/>
<bean id="testAdvice" class="com.test.TestAdvice">
</bean>
<bean id="testAdvisor"
class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
<property name="advice" ref="testAdvice" />
<property name="expression" value="execution(* *.home(..))" />
</bean>
和实际的建议
public class TestAdvice implements AfterReturningAdvice {
protected final Log logger = LogFactory.getLog(getClass());
public void afterReturning(Object returnValue, Method method, Object[] args,
Object target) throws Throwable {
logger.info("Called after returning advice!");
}
}
甚至可以对带注释的 Controller 提出建议吗?我正在使用 Spring 2.5。
最佳答案
可以对带注释的 Controller 提出建议。
我假设您想在执行带有 @Controller
注释的类中的所有方法后提出建议。
这是一个例子:
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class ControllerAspect {
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controllerBean() {}
@Pointcut("execution(* *(..))")
public void methodPointcut() {}
@AfterReturning("controllerBean() && methodPointcut() ")
public void afterMethodInControllerClass() {
System.out.println("after advice..");
}
}
如果你想使用带有 AspectJ 语法的 Spring AOP,你还需要一个这样的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="controllerAspect" class="controller.ControllerAspect" />
<aop:aspectj-autoproxy>
<aop:include name="controllerAspect" />
</aop:aspectj-autoproxy>
</beans>
注意:使用 Spring AOP,Spring 容器只会编织 Spring bean。如果 @Controller
对象不是 Spring bean,则必须使用 AspectJ 编织。
关于java - Spring AOP 关于注解 Controller 的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3310115/