Getting Spring beans programmatically

Something very common in projects with Spring is the need to get Spring beans in objects not managed by Spring. One example is when you are developing a custom manner to audit Hibernate entities using event listeners (this is subject to another post, actually).

The better option we have to allow this is to create a bean that implements the org.springframework.context.ApplicationContextAware interface. According to the documentation:

Implementing this interface makes sense for example when an object requires access to a set of collaborating beans. Note that configuration via bean references is preferable to implementing this interface just for bean lookup purposes.

A possible and simple implementation of this interface is:

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

public class ContextProvider implements ApplicationContextAware {

    private static ApplicationContext CONTEXT;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CONTEXT = applicationContext;

     * Get a Spring bean by type.
    public static <T> T getBean(Class<T> beanClass) {
        return CONTEXT.getBean(beanClass);

     * Get a Spring bean by name.
    public static Object getBean(String beanName) {
        return CONTEXT.getBean(beanName);


Take a look at the class above. It’s a simple bean (annotated with @Component) that implements the referenced Spring interface and, because of this, is notified about the creation of the Spring context.

When this happens, the Spring application context is put in an unique (static) object. This way, the static methods #getBean can find any managed bean making use of Spring context.

If you want to see an example of this working, take a look at this example project in my GitHub account.

See you.


Let me your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s