什么是CDI的InjectionPoint的Spring DI相当? [英] What is the Spring DI equivalent of CDI's InjectionPoint?

查看:768
本文介绍了什么是CDI的InjectionPoint的Spring DI相当?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Spring的bean生成器方法,它知道谁调用了它,所以我从以下代码开始:

I would like to create a Spring's bean producer method which is aware who invoked it, so I've started with the following code:

@Configuration
public class LoggerProvider {

    @Bean
    @Scope("prototype")
    public Logger produceLogger() {
        // get known WHAT bean/component invoked this producer 
        Class<?> clazz = ...

        return LoggerFactory.getLogger(clazz);
    }
}

如何获取 / strong>想要注入bean?

How can I get the information who wants to get the bean injected?

我正在寻找一些相当于 CDI的 InjectionPoint 在Spring world。

I'm looking for some equivalent of CDI's InjectionPoint in Spring world.

推荐答案

据我所知,Spring没有这样的概念。

As far as I know, Spring does not have such a concept.

然后只有知道处理的点是一个 BeanPostProcessor

Then only thing that is aware of the point that is processed is a BeanPostProcessor.

示例:

@Target(PARAMETER)
@Retention(RUNTIME)
@Documented
public @interface Logger {}

public class LoggerInjectBeanPostProcessor implements BeanPostProcessor {   
    public Logger produceLogger() {
        // get known WHAT bean/component invoked this producer
        Class<?> clazz = ...    
        return LoggerFactory.getLogger(clazz);
    }


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

    @Override
    public Object postProcessAfterInitialization(final Object bean,
            final String beanName) throws BeansException {

        ReflectionUtils.doWithFields(bean.getClass(),
                new FieldCallback() {
                     @Override
                     public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
                         field.set(bean, produceLogger());
                     }
                },
                new ReflectionUtils.FieldFilter() {
                     @Override
                     public boolean matches(final Field field) {
                          return field.getAnnotation(Logger.class) != null;
                     }
                });

        return bean;
    }
}

这篇关于什么是CDI的InjectionPoint的Spring DI相当?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆