Spring AOP 不工作

问题描述 投票:0回答:2

我正在尝试创建一些注释,在访问某些受保护的资源之前检查安全上下文的权限。我编写了一个与我想要实现的非常相似的示例代码,但是当我调用 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>
java spring aop aspectj spring-aop
2个回答
3
投票

尝试用这个改变你的注释

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

}

0
投票

就我而言,我可以告诉你,使用 Spring 3.X,配置中的注释是不必要的。 有依赖就足够了:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

这样就可以使用AspectJ注释了:

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

您需要使用@Aspect和@Component来注释该类。

© www.soinside.com 2019 - 2024. All rights reserved.