gpt4 book ai didi

java - 有没有一种方便的方法来获取 Spring Bean/Service 的名称?

转载 作者:行者123 更新时间:2023-11-30 10:50:04 36 4
gpt4 key购买 nike

我可以执行 SomeSpringService.class.getSimpleName() 并将第一个字母小写以获得默认的 bean 名称,但我想知道是否有一个简单的 Spring 函数可以为我找到这个?简单的意思是我没有获取应用程序上下文,或者没有构建工厂等。

谢谢

更新:当前黑客攻击

@Service
public class ServiceSelector
{
@Autowired
Map<String, IThing> implementations;

public SomethingInterface getDecisionStrategy(AnEnum type)
{
SomethingInterface something;

switch (type)
{
case ONE:
implementation = findInstance(Impl1.class);
break;
case TWO:
implementation = findInstance(Impl2.class);
break;
default:
implementation = findInstance(Impl2.class);
}
return implementation;
}

private SomethingInterface findInstance(Class clazz)
{
String className = clazz.getSimpleName();
String defaultBeanName = Character.toLowerCase(className.charAt(0)) + className.substring(1);
return implementations.get(defaultBeanName);
}
}

最佳答案

您的 bean 可以实现 BeanNameAware,因此您必须在您的类中添加 setBeanName(String beanName)。 Spring IoC 将返回您的 bean 名称。

例如:

public class Control implements BeanNameAware{
private String beanName;
@Override
public void setBeanName(String s) {
this.beanName = beanName;
}
}

关于java - 有没有一种方便的方法来获取 Spring Bean/Service 的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35192339/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com