问题
I'm trying the get Bean class name without initialize the bean. I need to know the class , I could get the bean from applicationContext and to check the class name from the bean instance, But I want to know the class with out actually creating/init the bean.. Is it possible ?
Object bean = applicationContext.getBean("beanName");
bean.getClass();
回答1:
You can't do this after creating the ApplicationContext
. Most ApplicationContext
implementations will refresh()
themselves and force instantiation of the beans.
What you can do is create a BeanFactoryPostProcessor
in which you get the target bean definition and check the bean class.
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String className = beanFactory.getBeanDefinition("").getBeanClassName();
}
But note, as the javadoc for getBeanClassName()
states
Hence, do not consider this to be the definitive bean type at runtime but rather only use it for parsing purposes at the individual bean definition level.
So use it with a grain of salt.
If you give us more details as to what you are trying to accomplish, there might be alternatives.
回答2:
The code provided by Sotirious will not work for the beans that have parent beans and for the beans that are defined using Java Config or using @Component
annotation (and similar annotatios like @Service
, @Repository
, @Component
).
Just an extension which checks if it is AnnotatedBeanDefinition
or if the bean has a parent:
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) {
String beanClassName = getBeanClassName(beanDefinitionName, beanFactory);
}
}
private String getBeanClassName(String beanName, ConfigurableListableBeanFactory beanFactory) {
String beanClassName;
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
if (beanDefinition instanceof AnnotatedBeanDefinition) {
AnnotationMetadata metadata = ((AnnotatedBeanDefinition) beanDefinition).getMetadata();
beanClassName = metadata.getClassName();
} else {
beanClassName = beanDefinition.getBeanClassName();
while (beanClassName == null) {
BeanDefinition parentBeanDefinition = beanFactory.getBeanDefinition(beanDefinition.getParentName());
beanClassName = parentBeanDefinition.getBeanClassName();
beanDefinition = parentBeanDefinition;
}
}
return beanClassName;
}
Note, this approach will not work in the case factory method is used. As Java Doc says:
Also, this may just be the class that a factory method is called on, or it may even be empty in case of a factory bean reference that a method is called on. Hence, do not consider this to be the definitive bean type at runtime but rather only use it for parsing purposes at the individual bean definition level.
来源:https://stackoverflow.com/questions/21435522/spring-bean-definition-get-bean-class