什么是CDI的InjectionPoint的Spring DI等价物?

时间:2012-03-13 13:51:10

标签: spring dependency-injection java-ee-6 cdi producer

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

@Configuration
public class LoggerProvider {

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

        return LoggerFactory.getLogger(clazz);
    }
}

如何获取想要注入bean的信息?

我正在寻找Spring世界中等价的CDI's InjectionPoint

2 个答案:

答案 0 :(得分:17)

Spring 4.3.0为bean生成方法启用InjectionPoint和DependencyDescriptor参数:

@Configuration
public class LoggerProvider {

    @Bean
    @Scope("prototype")
    public Logger produceLogger(InjectionPoint injectionPoint) {
        Class<?> clazz = injectionPoint.getMember().getDeclaringClass();

        return LoggerFactory.getLogger(clazz);
    }
}

顺便说一句,the issue for this feature SPR-14033链接到a comment on a blog post,链接到此问题。

答案 1 :(得分:6)

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

然后,只有知道处理点的事物才是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;
    }
}