Use case of BeanNameAware

roundAbout :

I can't figure out any use case of BeanNameAware interface except for logging the name of bean itself.

I did my research but I could not find a single person who wrote something other than just printing the bean name after the bean has been initialized. Does it have any real use case?

Aniket Sahrawat :

BeanNameAware can be used where we have an multiple classes subclassing a abstract class and would like to know the name of those particular bean in order to use their functionality, do something if bean name follows certain pattern, manipulate them, etc. Let's take an example and understand it:

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 
    }
}

And we have a service method that takes instance of all Parent class and invokes abstract void doFilter() method implementation:

@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
            }

        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144225&siteId=1