首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@ AOP @PostConstruct Spring AOP ineterception

@ AOP @PostConstruct Spring AOP ineterception
EN

Stack Overflow用户
提问于 2017-02-16 09:56:08
回答 1查看 1.5K关注 0票数 1

我正在尝试编写一个可以拦截PostConstruct方法的方面。我研究了有关SO和其他方面的相关问题,下面是我到目前为止所得到的:

Spring配置

代码语言:javascript
复制
@Configuration
@EnableAspectJAutoProxy
@EnableLoadTimeWeaving
@...//other config annotations
public class WebConfiguration {

    @Bean
    public CommonAnnotationBeanPostProcessor commonAnnotationBeanPostProcessor() {
        return new CommonAnnotationBeanPostProcessor();
    }
    ... // etc

}

注释:

代码语言:javascript
复制
@Retention(RetentionPolicy.RUNTIME)
public @interface Secured {
    Permission[] permissions() default {};
}

豆子

代码语言:javascript
复制
@Component
@Scope("request")
public class SomeWebBean {

    @Secured(permissions = Permission.SOME_PERMISSION)
    @PostConstruct
    public void secure() {
        ... // some stuff
    }

}

相貌

代码语言:javascript
复制
@Component
@Aspect
public class SecuredAspect {

    @Before("@annotation(secured)")
    public void doAccessCheck(Secured secured) {
        ... // actually do the access check
    }

}

如果我从一个页面调用someWebBean.secure(),那么就会调用方面。但是,在创建bean时不会调用它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-17 16:56:23

因此,作为对未来我的注意-这绝对不能用这种方式使用Spring。

但是,通过实现BeanPostProcessor也可以达到以下效果:

代码语言:javascript
复制
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;
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42270469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档