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

Pio*_*cki 13 spring dependency-injection producer cdi java-ee-6

我想创建一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到这些信息想要得到这个bean注入?

我正在寻找一些在Spring世界中相当于CDI的东西InjectionPoint.

Are*_*rff 18

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这个功能SPR-14033的问题链接到链接到这个问题的博客文章的评论.


Ral*_*lph 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;
    }
}
Run Code Online (Sandbox Code Playgroud)