usr-local-ΕΨΗΕΛΩΝ
usr-local-ΕΨΗΕΛΩΝ

Reputation: 26904

How to self-check the Spring bean scope?

My project provides a number (a nuuuuumbeeeeer) of base classes that developers may extend to their comfort and have to declare as Spring beans into XML configuration.

I am already aware that annotation config is inherited from the base class, but we mainly use XML

@SpringAnnotation
public abstract class Parent{}

//Will apply any @SpringAnnotation
public class Child{}

What I want to do is a self check in the base class. If a developer forgets to set the scope of a bean to the documented value (say, "request", for the current example), I would like the inherited bean to throw an exception reminding the developer to change the scope.

E.g.

public void afterPropertiesSet()
{
    if (!thisBean.getScope().equals("request"))
        throw new BeansException("Sorry but this bean works only when it is a request bean");
}

I have seen that Spring does not define any kind of BeanDefinitionAware which might inject the bean's own definition (along with scope and a lot of stuff) into the bean itself.

Any idea? I may come with a self-made solution soon.

Upvotes: 2

Views: 1064

Answers (1)

araknoid
araknoid

Reputation: 3125

You can define a bean implementing the BeanFactoryPostProcessor interface.

As reported in the BeanFactoryPostProcessor Spring doc, a bean implementing BeanFactoryPostProcessor is called when all bean definitions will have been loaded, but no beans will have been instantiated yet. This way you will be able to read all the beans definitions and check if the beans are properly configured.

This is an example:

public class CustomBeanFactory implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (String beanName : beanFactory.getBeanDefinitionNames()) {

            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

            // Analyze the bean definition

        }
    }
}

Last but not least, remember that a BeanFactoryPostProcessor may interact with and modify bean definitions, but never bean instances. Doing so may cause premature bean instantiation, violating the container and causing unintended side-effects. If bean instance interaction is required, consider implementing BeanPostProcessor instead.

Upvotes: 3

Related Questions