我正在尝试获取 Bean 类名而不初始化 bean。
我需要知道这个类,我可以从 applicationContext 获取 bean 并从 bean 实例中检查类名,但是我想知道这个类而不实际创建/初始化 bean..
是否可以 ?
Object bean = applicationContext.getBean("beanName");
bean.getClass();
最佳答案
创建 ApplicationContext
后,您无法执行此操作.最ApplicationContext
实现将 refresh()
自己并强制实例化 bean。
您可以做的是创建一个 BeanFactoryPostProcessor
您可以在其中获取目标 bean 定义并检查 bean 类。
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String className = beanFactory.getBeanDefinition("").getBeanClassName();
}
但请注意,作为
getBeanClassName()
的 javadoc状态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.
所以用一粒盐。
如果您向我们提供有关您要完成的工作的更多详细信息,则可能有其他选择。
关于Spring bean定义——获取bean类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21435522/