sat*_*shi 3 spring spring-mvc spring-aop
我正在编写一个几乎完全受登录保护的网站(我正在使用Spring Security).但是有些页面没有受到保护(主页,登录页面,注册页面,忘记密码页面......),我想要实现的是:
redirectTo注释元素中指定的页面)当然我想避免将它放在每个控制器方法中:
if(loggedIn())
{
// Redirect
}
else
{
// Return the view
}
Run Code Online (Sandbox Code Playgroud)
因此我想使用AOP.
我创建了Annotation @NonSecured,我编写了以下Aspect:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
示例注释方法:
@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
}
}
Run Code Online (Sandbox Code Playgroud)
applicationContext.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>
Run Code Online (Sandbox Code Playgroud)
问题是redirect(...)该方面的方法永远不会被调用.一般来说方面工作正常,实际上将调用方面中的以下方法:调用以下建议但不调用控制器方法.
@Around("execution(* *(..))")
public void redirect(ProceedingJoinPoint point) throws Throwable
{
point.proceed();
}
Run Code Online (Sandbox Code Playgroud)
我的切入点我做错了吗?
谢谢.
更新:此问题中的最后一个片段被调用但仍未调用控制器方法.
@satoshi,我认为您遇到的问题是因为您使用的是Spring-AOP,它只能为带接口的bean创建AOP代理 - 在您的情况下,控制器没有接口.
修复可能是使用AspectJ使用编译时/加载时间编织,并且不使用Spring AOP OR在类路径中使用cglib jar并强制基于cglib的代理创建:
<aop:aspectj-autoproxy proxy-target-class="true"/>
Run Code Online (Sandbox Code Playgroud)
更新:编译时编织可以使用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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11570 次 |
| 最近记录: |