java - BeanNameAware 的用例

标签 java spring

除了记录 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/

相关文章:

java - 如何从库项目调用主项目中的类/方法?

java - 如何在 Java 中使用 Column.isin?

Java for 循环总是返回 true

java - 如何用选定的颜色填充网格上选定的单元格?

java - 在Grails中使用Java编写的@Controller

java - Spring启动错误org.hibernate.MappingException : Could not determine type

SpringIntegration : Service-Activator not invoking method

java - 获取网页的发布日期

java - 连接一个本身有构造函数的 Bean

java - Google Drive Webhook 通知请求正文为空