我想创建一个春天的bean producer方法,它意识到谁调用它,所以我已经开始了以下代码:

@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注入?

我正在寻找一些相同的CDI的InjectionPoint 在春天世界中。

有帮助吗?

解决方案

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

然后只有知道被处理的点的东西是 beanpost processor


示例:

@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;
    }
}
.

其他提示

Spring 4.3.0启用注入点 Bean生产方法的参数和依赖性Descriptor参数:

@Configuration
public class LoggerProvider {

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

        return LoggerFactory.getLogger(clazz);
    }
}
.

顺便说一下,这个特征SPR-14033的问题SPR-14033 链接到关于博客文章的评论哪个链接到这个问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top