Sub topic 7
Aware Interfaces
This chapter assumes you know core Java (interfaces, annotations), basic Spring dependency injection (@Component, @Autowired, @Configuration, @Bean), and how to run a Spring or Spring Boot application. It covers the Aware callbacks that run during a bean's creation, and it leaves out the init and destroy callbacks that come before and after them.
What an Aware interface is
Most beans never need to know about the container. They declare dependencies in a constructor, and Spring supplies them. Occasionally a bean needs something the container itself holds: its own bean name, the ClassLoader, the ApplicationContext, or the Environment.
An Aware interface is a callback interface with one setter method. If your bean implements it, Spring calls that setter and hands you the matching infrastructure object. The name of each interface says what you receive: BeanNameAware gives you the bean name, ApplicationContextAware gives you the context.
Aware interfaces are a form of dependency lookup, and they tie your class to Spring. Use them in infrastructure code such as base classes, framework extensions and library glue. Ordinary business classes should not need them.
Where Aware callbacks fit in the lifecycle
Spring creates a bean in a fixed sequence. The container instantiates the object, populates its properties, and then calls the Aware callbacks. After that come the BeanPostProcessor "before initialization" step, the init callbacks, and the "after initialization" step.
Two consequences follow:
- The constructor runs before any Aware setter. You cannot use the injected infrastructure object inside the constructor.
- Aware setters run before
@PostConstructandafterPropertiesSet. Both init callbacks can therefore rely on Aware values.
The common Aware interfaces
| Interface | Method | What you receive |
|---|---|---|
| `BeanNameAware` | `setBeanName(String)` | The name of the bean in the container |
| `BeanClassLoaderAware` | `setBeanClassLoader(ClassLoader)` | The class loader used to load the bean class |
| `BeanFactoryAware` | `setBeanFactory(BeanFactory)` | The owning bean factory |
| `EnvironmentAware` | `setEnvironment(Environment)` | Properties and profiles |
| `ResourceLoaderAware` | `setResourceLoader(ResourceLoader)` | A loader for classpath and file resources |
| `ApplicationEventPublisherAware` | `setApplicationEventPublisher(...)` | A publisher for application events |
| `MessageSourceAware` | `setMessageSource(MessageSource)` | The message source for i18n |
| `ApplicationContextAware` | `setApplicationContext(ApplicationContext)` | The full application context |
BeanNameAware, BeanClassLoaderAware and BeanFactoryAware are defined in org.springframework.beans.factory. The other interfaces in the table are in org.springframework.context, except EnvironmentAware, which is in org.springframework.context as well. All of them are called in a defined order, which the next section shows.
Seeing the order
The following bean implements several Aware interfaces and prints a line in each callback. The @PostConstruct line shows where init callbacks begin.
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class AwareBean implements BeanNameAware, BeanFactoryAware,
EnvironmentAware, ApplicationContextAware {
public AwareBean() {
System.out.println("constructor");
}
@Override
public void setBeanName(String name) {
System.out.println("BeanNameAware: " + name);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) {
System.out.println("BeanFactoryAware: " + beanFactory.getClass().getSimpleName());
}
@Override
public void setEnvironment(Environment environment) {
System.out.println("EnvironmentAware: profiles="
+ String.join(",", environment.getActiveProfiles()));
}
@Override
public void setApplicationContext(ApplicationContext context) {
System.out.println("ApplicationContextAware: " + context.getDisplayName());
}
@PostConstruct
void init() {
System.out.println("@PostConstruct");
}
}Running this in a context prints, in order:
constructorBeanNameAware: awareBeanBeanFactoryAware: DefaultListableBeanFactoryEnvironmentAware: profiles=followed by any active profilesApplicationContextAware: ...with the context's display name@PostConstruct
The name awareBean is the default name Spring derives from the class name. BeanNameAware and BeanFactoryAware are handled directly by the bean factory. Interfaces such as EnvironmentAware and ApplicationContextAware are handled by a built-in BeanPostProcessor, the ApplicationContextAwareProcessor, which Spring registers when it prepares the context.
Why the context-based Aware interfaces depend on a post-processor
The distinction matters in one situation: a plain BeanFactory without an ApplicationContext. A bean factory that is used on its own calls the BeanNameAware, BeanClassLoaderAware and BeanFactoryAware callbacks. It does not call ApplicationContextAware or EnvironmentAware, because the ApplicationContextAwareProcessor is only added by the application context. In normal Spring and Spring Boot applications you always have a context, so you rarely see this difference.
The same mechanism has a second effect. Because ApplicationContextAwareProcessor is itself a BeanPostProcessor, the context-level Aware callbacks run in the "before initialization" step. They run before your own post-processors' "before" methods only if those post-processors are ordered after it. In practice you should treat the Aware callbacks as complete before @PostConstruct and not depend on their position relative to custom post-processors.
When to use an Aware interface, and when not to
Prefer injection. Most uses of Aware interfaces have a simpler equivalent:
| You want | Prefer | Instead of |
|---|---|---|
| Property values | `Environment` or `@Value` injected by constructor | `EnvironmentAware` |
| Publish an event | Inject `ApplicationEventPublisher` | `ApplicationEventPublisherAware` |
| Load a resource | Inject `ResourceLoader` | `ResourceLoaderAware` |
| Look up another bean on demand | `ObjectProvider<T>` | `ApplicationContextAware` and `getBean` |
The infrastructure types in this table (Environment, ApplicationEventPublisher, ResourceLoader, and ApplicationContext itself) are registered as resolvable dependencies, so constructor injection works for them. Constructor injection also makes the dependency visible, final, and easy to supply in a unit test.
Aware interfaces remain the right tool in a few cases:
BeanNameAware: no injection equivalent exists for a bean's own name. It is useful for logging, metrics tags or registering the bean under its name elsewhere.BeanFactoryAware: a library class may need to look up beans dynamically by type or name at runtime.- Framework code: code that must work across many Spring versions or without constructor control, for example a base class that subclasses cannot easily extend with new constructor arguments.
Common errors
Using the injected object in the constructor. The Aware setter has not run yet, so the field is null. Move the code into the setter, or into a @PostConstruct method.
Calling getBean everywhere. A class that holds an ApplicationContext and calls getBean on each use hides its real dependencies and becomes hard to test. It also makes the class a service locator. If the purpose is to get a fresh prototype instance, use ObjectProvider, which the scopes chapters cover.
Expecting Aware callbacks on objects you create yourself. Calling new AwareBean() yourself does not trigger any callback. Only beans created and managed by the container are processed.
Assuming a static ApplicationContext holder is safe. Some code stores the context in a static field from setApplicationContext. This breaks when more than one context exists, such as in tests that start several contexts, and it creates a hidden global. Avoid it.
Mixing up the bean name. For a @Component the name is derived from the class name with a lowercase first letter. For a @Bean method it is the method name unless you set a name explicitly. setBeanName always reports the name the container actually registered.
Summary of key points
- An Aware interface gives a bean access to one piece of container infrastructure through a setter.
- Aware callbacks run after the constructor and property population, and before
@PostConstructandafterPropertiesSet. BeanNameAware,BeanClassLoaderAwareandBeanFactoryAwarework with a plain bean factory. The context-level interfaces need an application context.- Prefer constructor injection of
Environment,ApplicationEventPublisher,ResourceLoaderorObjectProviderover the matching Aware interface. - Keep Aware interfaces for infrastructure code where the dependency cannot be injected.
Exercise
A bean implements ApplicationContextAware and uses the context field inside its constructor. What happens, and where should the code go instead?
Show answer
The field is null in the constructor, so the code throws a NullPointerException. Spring calls setApplicationContext only after it has instantiated the object and populated its dependencies. Move the code into the setter itself or into a @PostConstruct method, which runs after all Aware callbacks. Better still, inject only the specific dependency you need through the constructor.
Exercise
You want a singleton service to publish application events. Should it implement ApplicationEventPublisherAware? Give the alternative.
Show answer
It does not need to. ApplicationEventPublisher is a resolvable dependency, so you can declare it as a constructor parameter and keep the field final. This keeps the dependency visible and simplifies unit tests, because you can pass a mock publisher directly.
Exercise
In the AwareBean example, which line prints first, BeanNameAware: awareBean or @PostConstruct, and why?
Show answer
BeanNameAware: awareBean prints first. Aware callbacks run right after the container populates the bean and before the initialization callbacks such as @PostConstruct.