我试图创建一些注解,在访问一些受保护的资源之前检查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>
2条答案
按热度按时间wn9m85ua1#
我尝试用这个来改变你的注解
pvabu6sv2#
在我的例子中,我可以告诉你,在Spring 3.X中,配置中的注解是不必要的。有依赖性就足够了:
这样你就可以使用AspectJ注解:
您需要同时使用@Aspect和@Component来注解类。+
还要确保切入点指向包中的正确位置,否则在日志中看不到任何内容,因为切入点找不到方法。例如,如果在“com.demo.messaging.MyClass.myMethod”下找到该方法,则需要类似于