pankaj12
pankaj12

Reputation: 193

what is need of applicationcontextAware in spring

hi I am reading applicatonContextAware in details and trying to understand what is need of ApllicationContextAware.

"Sometimes it is needed to access context object inside bean class to create another bean. But the context object is created into another class, how we access this context object inside the bean class, once it is created inside the invoking bean factory class. This can be achieved using ApplicationContextAware class instance variable."

In pratically which condition we should use different contextAware. please.

Upvotes: 1

Views: 10596

Answers (1)

kuhajeyan
kuhajeyan

Reputation: 11017

Spring beans are managed by spring application container, when spring application stars it scan for beans which implements certain interfaces (there many interfaces like this such as BeanFactory Interfaces, ResourceAware, MessageSource aware, etc) 'ApplicationContextAware' is one of them, it has one method

void setApplicationContext(ApplicationContext applicationContext)
                    throws BeansException

and allows instance to use application context, this context will contain all the beans that are currently available to application, so for example if you need to look up some beans or access some application file resource or even publishing some application wide events, you can you this in your bean class.

@Component
public MyClass implements ApplicationContextAware{

private ApplicationContext context;

void setApplicationContext(ApplicationContext applicationContext)
                        throws BeansException
{
   context = applicationContext;
}

public void work(){
    MyOtherClass otherClass = context.getBean(MyOtherClass.class);
    Resource image =   context.getResource("logo.img");        
}

}

In new spring: Life is even easier for you,

Just call @Inject ApplicationContext context; or @Autowired ApplicationContext context;

to get your application context.

Upvotes: 3

Related Questions