【问题标题】:How to intercept EJB's when loaded加载时如何拦截 EJB
【发布时间】:2013-08-22 12:57:14
【问题描述】:

我有一些 EJB(用 @Stateless 注释)在我调用它们时加载(即它们不是 当我的应用程序服务器启动时急切地加载)。

其中一些包含自定义方法注释,我们称之为@Foo。

我想找到一种方法在我的应用程序服务器 (AS) 时扫描所有这些 靴子并找到用@Foo注释的那些。

到目前为止,我已经在 web.xml 中注册了一个名为的生命周期侦听器 在 AS 启动时。

  • PS#1:@PostConstruct 在我的 EJB 首次被调用时被调用 我的 AP 启动后可能会在稍后的时间。
  • PS#2:当我的 EJB 在 JNDI 上注册时是否会引发事件?
  • PS#3:当您将 Spring 配置为扫描所有类时,我认为 Spring 会做类似的事情 在一个包下

【问题讨论】:

  • @Foo 是 CDI 合格者吗?

标签: spring jakarta-ee ejb cdi


【解决方案1】:

如果 EJB 是由 Spring 构建的,那么您可以使用 Spring bean 后处理器(这是 Spring 在执行扫描时使用的)。

@Component
public class FooFinder implements BeanPostProcessor {

    List<Method> fooMethods = new ArrayList<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> targetClass = AopUtils.getTargetClass(bean);
        for (Method method : targetClass.getDeclaredMethods()){
            for (Annotation annotation : AnnotationUtils.getAnnotations(method)){
                if (annotation instanceof Foo){
                    fooMethods.add(method);
                }
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

还要注意...小心注入到 BeanPostProcessor 中的依赖项。您可能会在 Spring 依赖图上产生问题,因为必须首先创建 BeanPostProcessors。如果您需要向其他 bean 注册该方法,请制作 BeanPostProcessor ApplicationContextAware 或 BeanFactoryAware,然后以这种方式获取 bean。

【讨论】:

    猜你喜欢
    • 2014-03-10
    • 2017-05-18
    • 2018-01-20
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多