Spring Boot
Application Context
Bean Management
Java
Dependency Injection

How to get bean using application context in spring boot

Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD

In the Spring Framework ecosystem, retrieving beans from the application context is a fundamental capability. Spring Boot expands upon this by providing an environment that simplifies dependency injection. Understanding how to access beans from the application context becomes crucial for dynamic and flexible applications. This article explores the methods and best practices for retrieving beans in Spring Boot.

Understanding Application Context

The application context in Spring Boot serves as a central registry for your application's components (or beans). The context is initiated when your Spring Boot application starts, and it automatically discovers and manages beans. It provides metadata-driven dependency injection and a means to retrieve beans manually when necessary.


Retrieving Beans Using ApplicationContext

The ApplicationContext interface offers several methods to access different types of beans. Here's a detailed look at the common methods employed:

1. Using @Autowired

In Spring Boot applications, the most common way to retrieve a bean is via dependency injection using the @Autowired annotation. This method supports constructor, setter, and field injection.

java
1@Service
2public class MyService {
3
4    private final MyRepository myRepository;
5
6    @Autowired
7    public MyService(MyRepository myRepository) {
8        this.myRepository = myRepository;
9    }
10
11    // Other methods
12}

In this example, MyRepository is automatically injected into MyService by Spring Boot.

2. Using ApplicationContext.getBean()

For cases where you need to access beans dynamically or where dependency injection is impractical, the getBean() method can be used.

java
1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.context.ApplicationContext;
3import org.springframework.stereotype.Component;
4
5@Component
6public class BeanRetriever {
7
8    @Autowired
9    private ApplicationContext applicationContext;
10
11    public Object retrieveBean(String beanName) {
12        return applicationContext.getBean(beanName);
13    }
14
15    public <T> T retrieveBean(Class<T> beanClass) {
16        return applicationContext.getBean(beanClass);
17    }
18}

3. Accessing Beans Programmatically

Sometimes, bean retrieval needs to be performed outside of the Spring context, such as within static methods.

Static Method Access

java
1public class StaticContextHolder implements ApplicationContextAware {
2
3    private static ApplicationContext context;
4
5    @Override
6    public void setApplicationContext(ApplicationContext applicationContext) {
7        context = applicationContext;
8    }
9
10    public static <T> T getBean(Class<T> requiredType) {
11        return context.getBean(requiredType);
12    }
13}

This allows you to retrieve beans without injecting the context:

java
MyRepository repo = StaticContextHolder.getBean(MyRepository.class);

Note: Consider dependency injection first, for cleaner and more testable code.

4. Conditional Bean Retrieval

Spring Boot also provides ways to determine the existence of a bean before retrieving it.

java
if (applicationContext.containsBean("myBean")) {
    MyBean myBean = (MyBean) applicationContext.getBean("myBean");
}

This method is useful for conditionally handling multiple configurations or optional dependencies.


Best Practices

  1. Prefer Dependency Injection: Always prefer using dependency injection (@Autowired) for cleaner and more maintainable code.
  2. Avoid Excessive Use of getBean(): Minimize direct calls to ApplicationContext.getBean(), as they may indicate a design issue.
  3. Test Considerations: Use Spring Boot's test capabilities (@SpringBootTest) to automatically manage the application context in your tests.
  4. Profile Management: Use Spring profiles to manage environment-specific beans and configurations effectively.

Key Points Summary Table

AspectDetails
Injection Method@Autowired for fields, setters, or constructors.
Dynamic AccessApplicationContext.getBean() for flexible retrieval.
Static AccessImplement ApplicationContextAware for static contexts.
Condition RetrievalUse containsBean() to check bean existence.
Coding PracticeFavor dependency injection for cleaner code.
Environment ProfilesUtilize profiles to manage configurations.

By thoroughly understanding how to access and manage beans in Spring Boot, you can build more dynamic, maintainable applications. Always strive to follow best practices and leverage the full power of Spring Boot's dependency injection framework.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD

All Rights Reserved.