Spring控制器未被代理

时间:2014-03-05 18:02:08

标签: spring-mvc spring-aop

我有一个类似下面的控制器类:

@Controller
class X extends BaseController{ 
    @RequestMapping()
    public String getX(){
    }
}

public class BaseController implements ServletContextAware {
}

我正在尝试添加如下所示的方面:

@Service
@Aspect
public class Foo{
   @Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
   public Object profileControllerAction(ProceedingJoinPoint pjp) 
                 throws Throwable {
      // do stuff
   }
}

但是,不调用aspect方法。我希望在调用控制器的getX()时执行它。

我看到spring mvc没有用代理包装我的控制器bean。这就是为什么这个方面没有效果的原因?

任何人都可以解释我如何获得所谓的方面。

控制器类位于: com.xyz.webapp.controller

Aspect类在 com.xyz.webapp

上下文文件位于WEB-INF中 上下文xml是:

<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"          
    default-lazy-init="true">
    <context:annotation-config/>  
    <context:component-scan base-package="com.xyz"/>    
    <aop:aspectj-autoproxy />

    <aop:config>  
        <aop:advisor id="serivcesApiAdvice" advice-ref="serivcesAdvice" pointcut="execution(* *..provider.*.*(..))" order="1"/>        
    </aop:config>   
    <bean id="serivcesAdvice" class="com.xyz.webapp.spring.xyzMethodInterceptor"/>    
</beans>

-----更多细节--- 我在我们的一个控制器方法中添加了以下代码。该列表包含所有控制器和我编写的方面。实际上,我认为它列出了我们所有的bean。如何在运行时查看应用程序中所有应用程序上下文的内容?

ApplicationContext context = ApplicationContextProvider.getApplicationContext();
System.out.println("context name:" + c.getDisplayName());
for(String s : context.getBeanDefinitionNames()){
    System.out.println(s);
}

它打印的上下文名称是:Root WebApplicationContext

1 个答案:

答案 0 :(得分:1)

上下文中的方面配置仅适用于该上下文。它只能处理那里声明的bean。

Spring在其根上下文和servlet上下文之间使用父子关系。因此,上述规则不适用。如果希望代理服务器代理其他方面行为,则需要将方面配置添加到servlet上下文中,该上下文扫描并生成@Controller bean。

请注意,您似乎正在进行冗余配置。您(我假设)根上下文是扫描应由servlet上下文扫描的包(包含@Controller类)。不要这样做,否则你最终会得到两个豆子或注射错误。

此外,

<context:annotation-config/>  
如果指定

,则

是多余的

<context:component-scan base-package="com.xyz"/>    

你可以摆脱它。

相关问题