Spring AOP无法正常工作

时间:2017-03-14 20:02:27

标签: java spring aop aspectj spring-aop

我正在尝试创建一些注释,在访问某些受保护资源之前检查securitycontext的权限。我编写了一个非常类似于我想要实现的示例代码,但是当我调用SomethingProtected()时,似乎该方面的@Before部分实际上从未被触发。任何帮助将不胜感激。

我有:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NeedsPermissions {
    boolean read() default true;
}

@Aspect
public class NeedsPermissionsAspect {
    @Before("execution(* *.*(..)) && @annotation(NeedsPermissions)")
    public void CheckPermissions(JoinPoint pjp, NeedsPermissions needsPermissions) throws Throwable {
        System.out.println("aspect");
        if (needsPermissions.read() == true) {
            SecurityContext securityContext = SecurityContext.getSecurityContext();
            MyUser user = securityContext.getUser();
            if (!user.read){
                throw new Exception("Not Allowed");
            }
        }
    }
}

@Configuration
@EnableAspectJAutoProxy
public class NeedsPermissionsConfig {
}

public class ProtectedResource {

    @NeedsPermissions
    public void SomethingProtected(){
        System.out.println("Something protected");
    }
}

<?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/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <aop:aspectj-autoproxy/>



    <!-- Aspect -->
    <bean id="needsPermissionsAspect" class="NeedsPermissionsAspect">
        <!-- configure properties of aspect here as normal -->
    </bean>

</beans>

1 个答案:

答案 0 :(得分:1)

尝试通过此方法更改注释

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AppConfig {

}
相关问题