方面未在Spring中执行 [英] Aspect not executed in Spring
本文介绍了方面未在Spring中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个几乎完全受登录保护的网站(我使用的是Spring Security)。但有些页面不受保护(主页、登录页、注册页、忘记密码页等)我想要实现的目标是:
- 如果用户在访问这些非安全页面时未登录, 正常显示
- 如果用户已登录,请重定向到
主页(或指向
redirectTo
注释元素中指定的页面)
当然,我希望避免将其放在每个控制器方法中:
if(loggedIn())
{
// Redirect
}
else
{
// Return the view
}
出于这个原因,我想使用AOP。
我创建了注释@NonSecured
,并编写了以下方面的代码:
@Aspect
public class LoggedInRedirectAspect
{
@Autowired
private UserService userService;
@Around("execution(@my.package.annotation.NonSecured * *(..))")
public void redirect(ProceedingJoinPoint point) throws Throwable
{
System.out.println("Test");
point.proceed();
}
}
带注释的方法示例:
@Controller
@RequestMapping("/")
public class HomeController
{
@NonSecured(redirectTo = "my-profile")
@RequestMapping(method = RequestMethod.GET)
public String index(Model model,
HttpServletRequest request) throws Exception
{
// Show home page
}
}
应用上下文.xml重要信息:
<context:annotation-config />
<context:component-scan base-package="my.package" />
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
<bean id="loggedInRedirectAspect" class="my.package.aspect.LoggedInRedirectAspect" />
<aop:aspectj-autoproxy proxy-target-class="true">
<aop:include name="loggedInRedirectAspect" />
</aop:aspectj-autoproxy>
问题是方面中的方法redirect(...)
从未被调用。方面总体工作正常,实际上方面中的以下方法将被调用:调用了以下通知,但没有为控制器方法调用。
@Around("execution(* *(..))")
public void redirect(ProceedingJoinPoint point) throws Throwable
{
point.proceed();
}
我是否在切入点中做错了什么?
谢谢。
更新:调用此问题中的最后一个代码段,但仍未为控制器方法调用。
推荐答案
@Satoshi,我认为您遇到的问题是因为您使用的是Spring-AOP,它只能为带有接口的Bean创建AOP代理--在您的情况下,控制器没有接口。
修复方法可能是使用AspectJ使用编译时/加载时编织,而不使用Spring AOP或在类路径中使用cglib JAR,并强制创建基于cglib的代理:
<aop:aspectj-autoproxy proxy-target-class="true"/>
更新: 编译时编织可以使用maven插件完成,showWeaveInfo配置将准确显示哪些类已经编织:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.10</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.6.10</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<outxml>true</outxml>
<verbose>true</verbose>
<showWeaveInfo>true</showWeaveInfo>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
这篇关于方面未在Spring中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文