出于调试目的,我想这样做:
@Autowired
private BeanDefinition myBeanDefinition;
即。在工厂创建bean之后,它应该将bean定义连接到它,这样我就可以很容易地看到它在调试过程中的来源。
或许还有另一种方法可以在运行时看到定义bean的位置?
答案 0 :(得分:2)
您可以使用BeanPostProcessor
:
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
public class AutowireBeanDefinitionPostProcessor implements BeanPostProcessor {
@Autowired
private ApplicationContext applicationContext;
@Override
public Object postProcessBeforeInitialization( Object bean, String beanName ) throws BeansException {
if( bean instanceof BeanDefinitionAware ) {
ConfigurableListableBeanFactory factory = ( (ConfigurableApplicationContext) applicationContext ).getBeanFactory();
BeanDefinition bd = factory.getBeanDefinition( beanName );
( (BeanDefinitionAware) bean ).setBeanDefinition( bd );
}
return bean;
}
@Override
public Object postProcessAfterInitialization( Object bean, String beanName ) throws BeansException {
return bean;
}
}
让你的bean实现BeanDefinitionAware
:
import org.springframework.beans.factory.config.BeanDefinition;
public interface BeanDefinitionAware {
void setBeanDefinition( BeanDefinition beanDefinition );
}
您可以将定义存储在字段中。