Spring bean定义——获取bean类 [英] Spring bean definition - get bean class

查看:53
本文介绍了Spring bean定义——获取bean类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取 Bean 类名而不初始化 bean.我需要知道这个类,我可以从 applicationContext 获取 bean 并从 bean 实例中检查类名,但我想知道这个类而不实际创建/初始化 bean..可能吗?

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();

推荐答案

在创建 ApplicationContext 后,您无法执行此操作.大多数 ApplicationContext 实现将 refresh() 自己并强制实例化 bean.

You can't do this after creating the ApplicationContext. Most ApplicationContext implementations will refresh() themselves and force instantiation of the beans.

您可以做的是创建一个 BeanFactoryPostProcessor,您可以在其中获取目标 bean 定义并检查 bean 类.

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();
}

但请注意,正如 getBeanClassName() 的 javadoc 所述

But note, as the javadoc for getBeanClassName() states

因此,不要认为这是运行时确定的 bean 类型而是仅将其用于单个 bean 的解析目的定义级别.

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.

所以用它加一点盐.

如果您向我们提供有关您要完成的工作的更多详细信息,可能会有其他选择.

If you give us more details as to what you are trying to accomplish, there might be alternatives.

这篇关于Spring bean定义——获取bean类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆