java 如何从 Spring 中的 bean 内部获取 bean 的 id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1199358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:36:09  来源:igfitidea点击:

How to get the id of a bean from inside the bean in Spring?

javaspringjavabeans

提问by David Rabinowitz

What is the easiest way to retrieve a bean id from inside that bean (in the Java code) without using a BeanPostProcessor to set a field?

在不使用 BeanPostProcessor 设置字段的情况下,从该 bean 内部(在 Java 代码中)检索 bean id 的最简单方法是什么?

The only way I can think of is something like this using a BeanPostProcessor:

我能想到的唯一方法是使用 BeanPostProcessor:

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    ((MyBean)bean).setName(beanName);
    return bean;
}

Is there a better way that doesn't require me to write an extra class or know the class of the bean in question? I tried searching through the docs and on Google, but I'm not really sure what I need to be looking for.

有没有更好的方法不需要我编写额外的类或知道有问题的 bean 的类?我尝试通过文档和谷歌搜索,但我不确定我需要寻找什么。

Thanks!

谢谢!

回答by David Rabinowitz

Just implement the org.springframework.beans.factory.BeanNameAwareinterface and you will get it automatically. It has one method:

只需实现 org.springframework.beans.factory.BeanNameAware接口,您就会自动获得它。它有一种方法:

void setBeanName(String name)