Spring Boot Aware Interfaces for Bean Lookup and DataSource Inspection

Spring provides several callback interfaces that let beans interact with the container itself. Two of the most practical are BeanFactoryAware and ApplicationContextAware. Below are concise patterns that I rely on daily.

BeanFactoryAware – type-safe bean retrieval

By implementing BeanFactoryAware we can expose a small static façade that hides the container from the rest of the codebase.

package demo.spring.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

@Component
public final class BeanLookup implements BeanFactoryAware {

    private static BeanFactory factory;

    @Override
    public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
        factory = beanFactory;
    }

    public static <T> T of(Class<T> requiredType) {
        return factory.getBean(requiredType);
    }

    public static <T> T of(String name, Class<T> requiredType) {
        return factory.getBean(name, requiredType);
    }

    public static Object of(String name) {
        return factory.getBean(name);
    }
}

ApplicationContextAware – runtime container introspection

ApplicationContextAware gives us the full ApplicationContext, which is useful when you need to inspect or manipulate beans at runtime. The following component prints the concrete DataSource implementation chosen by Spring Boot and lists every bean definition in the order they were registered.

package demo.spring.probe;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
public class ContextProbe implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        DataSource ds = ctx.getBean(DataSource.class);
        System.out.println("Active connection pool: " + ds.getClass().getCanonicalName());

        String[] names = ctx.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }
}

These two snippets are enough to cover most "get me a bean" or "what’s actually running" scenarios with out scattering container code through out your services.

Tags: Spring Boot BeanFactoryAware ApplicationContextAware DataSource Bean Lookup

Posted on Tue, 27 Oct 2026 16:21:46 +0000 by Buddski