除了记录 bean 本身的名称外,我想不出 BeanNameAware
接口(interface)的任何用例。
我做了我的研究,但我找不到一个人除了在 bean 初始化后打印 bean 名称之外还写了其他东西。它有任何实际用例吗?
最佳答案
BeanNameAware
可以用于我们有多个类子类化一个抽象类的地方,并且想知道那些特定 bean 的名称以便使用它们的功能,如果 bean 名称遵循特定模式则执行某些操作,操纵它们等。让我们举个例子来理解它:
abstract class Parent implements BeanNameAware {
String beanName;
void setBeanName(String beanName) {
this.beanName = beanName;
}
abstract void doFilter();
}
@Component
class Child1 extends Parent {
@Override
void doFilter() {
// some impl
}
}
@Component
class Child2 extends Parent {
@Override
void doFilter() {
// some impl
}
}
我们有一个服务方法,它获取所有 Parent
类的实例并调用 abstract void doFilter()
方法实现:
@Service
class SomeService{
@Autowired
Parent[] childs; // injecting all Child*
void doSomethingWithChilds() {
for(Parent child: childs) {
child.doFilter(); // invoking their doFilter() impl
String currentChildName = child.beanName;
// We now know the name of current child* bean
// We can use it for manipulating the child* instance
// This is useful because each child instance will have a different bean name
if(currentChildName.equals("child2")) {
// do something special with child2
}
}
}
}
关于java - BeanNameAware 的用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57839044/