Accessing Spring Bean Inside A Pojo

Java Spring Decoded
Javarevisited
Published in
1 min readApr 10, 2023

Suppose we have a Pojo class MyPojo , which want to access an object from Spring Bean , How can we do that ?

A Simple Approach would be to use ApplicationContextAware Interface of Spring , We can implement this class to return Bean of desired class in Our Pojo.

As We can see Below , we want a Bean of MyBean Class in MyPojo Class , MyBean Class is managed by Spring while MyPojo is managed by developer, So we are using the getBean() method of ApplicationContextAware Interface .

we just need to Pass the class name here and just like that we will get the spring managed object in our Pojo .

class MyPojo{
MyBean myBean = SpringContext.getBean(MyBeanClass.class);
}

@Component
public class SpringContext implements ApplicationContextAware {

private static ApplicationContext context;

public static <T extends Object> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}

@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
setContext(context);
}


private static synchronized void setContext(ApplicationContext context) {
SpringContext.context = context;
}
}

P.S :-

Some of you can think why can’t we directly use Autowired Annotation in the pojo and inject the bean , doing so can give a NPE as Our Pojo is not managed by Spring , its dependencies will not be injected .

--

--

Java Spring Decoded
Javarevisited

All Articles related to java , spring , Backend Development and System Design.