DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)
  • Spring Beans With Auto-Generated Implementations: How-To
  • The Magic of Spring Data
  • Spring Boot Centralized Logging with Graylog

Trending

  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Bean Lifecycle: Using Spring Aware Interfaces

Spring Bean Lifecycle: Using Spring Aware Interfaces

Learn more about using Aware interfaces to access Spring bean lifecycle events.

By 
John Thompson user avatar
John Thompson
·
Aug. 30, 19 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
77.8K Views

Join the DZone community and get the full member experience.

Join For Free

Spring bean Aware interface

Through Spring Aware interfaces, you can access Spring bean lifecycle events.

Spring Aware interfaces allow you to look into the inner workings of the Spring Framework. Through Spring Aware interfaces, you can access the Spring context, or Spring bean lifecycle events.

Your Spring beans might require access to framework objects, such as ApplicationContext, BeanFactory, and ResourceLoader. To gain access, a bean can implement one of the many Aware interfaces of the Spring Framework.

Want to learn more about various aspects of the Spring bean lifecycle? Check out this post: Working With Resources in Spring!

When a bean implements an Aware interface, the Spring Framework injects a particular framework object to the bean through a callback-style method. The object Spring injects depends on the interface which the bean implements. For example, if the bean implements the ApplicationContextAware interface, Spring will inject an ApplicationContext object into the bean.

In this post, we will learn about the Spring aware interfaces, particularly ApplicationContextAware, BeanFactoryAware, and BeanNameAware interfaces.

In the bean lifecycle, the Spring Framework calls the aware interface methods after populating bean properties and just before pre initialization with BeanPostProcessor.

Aware interfaces Callbacks in Bean Lifecycle

The ApplicationContextAware Interface

In Spring beans, you might require access to the ApplicationContext. For example, if your bean needs to look up some other beans. Similarly, if your bean needs access to some application file resource in your bean or even publish some application events, you need access to the ApplicationContext.

Spring provides an ApplicationContextAware interface that allows beans access to the ApplicationContext. This interface provides a single setApplicationContext method.

void setApplicationContext(ApplicationContext applicationContext)
throws BeansException


The following code shows the use of ApplicationContextAware.

package guru.springframework.springawaredemo.awareimpls;
import guru.springframework.springawaredemo.domain.User;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextAwareImpl implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
User user = (User) applicationContext.getBean("user");
System.out.println("User Id: " + user.getUserId() + " User Name :" + user.getName());
}
}


The preceding code is of a bean that implements ApplicationContextAware. The code overrides the setApplicationContext() method to lookup another bean with the id user using the injected ApplicationContext.

The BeanFactoryAware Interface

Beans might need access to the bean factory that created it, say to call any service from the bean factory.
Should you need to obtain a reference to the bean factory, implement the BeanFactoryAware interface. This interface provides the setBeanFactory() method.

void setBeanFactory(BeanFactory beanFactory)


The preceding setBeanFactory() is a callback that supplies the owning factory to the bean instance.
Here is an example of a bean that implements the BeanFactoryAware Interface.

package guru.springframework.springawaredemo.awareimpls;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
public class BeanFactoryAwareImpl implements BeanFactoryAware {
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println(beanFactory.getBean("user"));
}
}


The BeanNameAware Interface

The BeanNameAware interface is implemented by beans that need access to its name defined in the Spring container. This interface provides the setBeanName() method.

void setBeanFactory(BeanFactory beanFactory)


The preceding setBeanFactory() is a callback that supplies the name of the bean.

Here is an example of a bean which implements the BeanNameAware Interface.

package guru.springframework.springawaredemo.awareimpls;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
public class BeanFactoryAwareImpl implements BeanFactoryAware {
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println(beanFactory.getBean("user"));
}
}


Summary

Although I covered only three, there are additional aware interfaces. The Aware API documentation provides complete details.

One interface I would like to specially mention is the ResourceLoaderAware interface. Implement this interface if a bean needs to load resources present in the classpath or file system. On implementing ResourceLoaderAware, your bean is notified of the ResourceLoader (typically the ApplicationContext) that it runs in. This is an alternative to a full ApplicationContext dependency via the ApplicationContextAware interface.

I’ll be writing a detailed post on ResourceLoaderAware that you can check out.

As an end note, I’m not particularly fond of the aware interfaces. Implementing them ties your application to the Spring Framework, thus inverting the whole inversion-of-control concept. In an ideal world, your application should not be aware of being managed by an ApplicationContext at all or tied to any framework objects.

Also, note that ApplicationContextAware is the legacy version that has been around at least since Version 2.0. @Autowired ApplicationContext applicationContext and @Inject ApplicationContext applicationContext are the newer mechanisms but they work in pretty much the same way. Although the newer ones require lesser typing of code, I’d probably go with ApplicationContextAware, because it semantically makes clear what it is about.

The source code for this post can be found here on GitHub.

Further Reading

Defining Bean Dependencies With Java Config in Spring Framework

Working With Resources in Spring

Spring Framework Interface (computing)

Published at DZone with permission of John Thompson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)
  • Spring Beans With Auto-Generated Implementations: How-To
  • The Magic of Spring Data
  • Spring Boot Centralized Logging with Graylog

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!