我正在尝试编写一个可以拦截PostConstruct方法的方面。我研究了有关SO和其他方面的相关问题,下面是我到目前为止所得到的:
Spring配置
@Configuration
@EnableAspectJAutoProxy
@EnableLoadTimeWeaving
@...//other config annotations
public class WebConfiguration {
@Bean
public CommonAnnotationBeanPostProcessor commonAnnotationBeanPostProcessor() {
return new CommonAnnotationBeanPostProcessor();
}
... // etc
}注释:
@Retention(RetentionPolicy.RUNTIME)
public @interface Secured {
Permission[] permissions() default {};
}豆子
@Component
@Scope("request")
public class SomeWebBean {
@Secured(permissions = Permission.SOME_PERMISSION)
@PostConstruct
public void secure() {
... // some stuff
}
}相貌
@Component
@Aspect
public class SecuredAspect {
@Before("@annotation(secured)")
public void doAccessCheck(Secured secured) {
... // actually do the access check
}
}如果我从一个页面调用someWebBean.secure(),那么就会调用方面。但是,在创建bean时不会调用它。
发布于 2017-02-17 16:56:23
因此,作为对未来我的注意-这绝对不能用这种方式使用Spring。
但是,通过实现BeanPostProcessor也可以达到以下效果:
public class SecureBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
Secured secured = bean.getClass().getAnnotation(Secured.class);
if (secured != null) {
// do your security test here, throw an exception, return false, however you like
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}https://stackoverflow.com/questions/42270469
复制相似问题