CDI注射点的弹簧二等价物是什么?
-
13-12-2019 - |
题
我想创建一个春天的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 链接到关于博客文章的评论哪个链接到这个问题。
不隶属于 StackOverflow