Monday, April 3, 2017

What is aware injection in spring

           What is aware injection in spring?

        Sometimes we need spring framework objects in our beans to perform some operations, for example reading ServletConfig and ServletContext parameters or to know the bean definitions loaded by the ApplicationContext. That’s why spring framework provides a bunch of * Aware interfaces that we can implant in our bean classes.
 org.springframework.beans.factory.Aware is the root marker interface for all these Aware interfaces. All of the *Aware interfaces are sub-interfaces of Aware and declare a single setter method to be implemented by the bean. Then Spring context uses setter –based dependency injection to inject the corresponding objects in the bean and make t available for our use.

Some of the important Aware interfaces are:
·         ApplicationContextAware – to inject ApplicationContext object.
·         BeanFactoryAware – to inject BeanFactory object.
·         BeanNameAware – to know the ban name defined in the configuration file.
·         ServletContextAware – to inject ServletContext object in MVC application example usage is to read context parameters and attributes.
·         servletConfigAware – to inject ServletConfig objects in MVC application. Example usage is to get servlet config parameters.

Let’s see these Aware interface usage in action by implementing few of them in a class that we will configure as spring bean.



ex:-

public class MyAwareService implements ApplicatonContextAware,BeanNameAware{
@Override
public void setApplicationContext(ApplicationCOntext ctx)throws BeansExcption {
System.out.println(“setApplicationContext called”);
System.out.println(“setapplicationcontext baean devination names=”+Arrays.toString(ctx.getBeanDefinationNames()));
}
@Override
public void setBeanName(String beanName){
System.out.println(“setBeanName called”);
System.out.println(“setBanName”” NEan Name definition in contedt =”+beanName);
}

}

1 comment: