关于带注释的控制器的Spring AOP建议 [英] Spring AOP Advice on Annotated Controllers
问题描述
我试图在带注释的控制器之后使用AOP进行一些处理.一切都在正常运行,但没有执行建议.
I am trying to use AOP to do some processing after an annotated controller. Everything is running with no errors, but the advice is not being executed.
这是控制器代码:
@Controller
public class HomeController {
@RequestMapping("/home.fo")
public String home(ModelMap model) {
model = new ModelMap();
return "home";
}
}
以及application-config中的设置
and the setup in application-config
<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!");
}
}
是否甚至可以对带注释的控制器提出建议?我正在使用Spring 2.5.
Is it even possible to have advice on annotated controllers? I am using Spring 2.5.
推荐答案
有可能对带注释的控制器提出建议.
It's possible to have advice on annotated controllers.
我假设您想在用@Controller
注释的类中执行所有方法之后提出建议.
I assume you want to advice after execution of all methods in classes annotated with @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..");
}
}
如果您想将Spring AOP与AspectJ语法一起使用,则还需要这样的配置文件:
If you want to use Spring AOP with AspectJ syntax, you also need a configuration file like this:
<?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编织.
Note: With Spring AOP, the Spring container will only weave Spring beans. If the @Controller
object isn't a Spring bean, you must use AspectJ weaving.
这篇关于关于带注释的控制器的Spring AOP建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!