7. Spring Beans & Application Context
Compilation successful (exit code 0), your code is syntactically correct. Copy it to your local IDE and run ./mvnw spring-boot:run to see Spring create and manage beans.Beans are the objects that form the backbone of your Spring application. They are created, wired, and managed by the Spring IoC container (the ApplicationContext). Understanding bean lifecycles, scopes, and configuration is essential for building efficient Spring Boot applications.
What is a Spring Bean?
A Spring bean is simply an object that is instantiated, assembled, and managed by the Spring IoC container. Any Java object can be a bean. Beans are defined using annotations or XML configuration.
@Service public class UserService { // This class is a Spring Bean private final UserRepository repository; public UserService(UserRepository repository) { // UserRepository is also injected as a bean this.repository = repository; } } @Repository public interface UserRepository extends JpaRepository<User, Long> { } // Also a Spring Bean
@Autowired private ApplicationContext context; then call context.getBeanDefinitionNames() to see all beans.Bean Scopes: Singleton vs Prototype
Bean scope defines how many instances of a bean Spring creates and how they are shared.
Singleton (Default)
One instance per Spring container. Most beans are singletons — this is efficient and ideal for stateless services.
@Service // Scope is SINGLETON by default public class UserService { // One instance shared across the entire application }
Prototype
New instance every time the bean is requested. Use for stateful beans.
@Component @Scope("prototype") public class ShoppingCart { // New instance created for each user session }
// Other scopes (only in web-aware ApplicationContext): @Scope("request") // One instance per HTTP request @Scope("session") // One instance per HTTP session @Scope("application") // One instance per ServletContext
The ApplicationContext
The ApplicationContext is the central interface in Spring that provides bean factory functionality and enterprise services. In Spring Boot, it is automatically created by SpringApplication.run().
@SpringBootApplication public class DemoApplication { public static void main(String[] args) { // This returns the ApplicationContext ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args); // You can retrieve beans by type or name UserService userService = context.getBean(UserService.class); // List all bean names String[] beanNames = context.getBeanDefinitionNames(); System.out.println("Beans count: " + beanNames.length); } }
Explicit Bean Configuration with @Bean
Sometimes you need to create a bean manually (e.g., configuring third-party libraries). Use @Bean in a @Configuration class.
@Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { // Custom configuration for RestTemplate return new RestTemplateBuilder() .setConnectTimeout(Duration.ofSeconds(5)) .setReadTimeout(Duration.ofSeconds(5)) .build(); } @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); return mapper; } } // Usage - Spring injects the configured bean @Service public class ApiService { private final RestTemplate restTemplate; public ApiService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } }
Bean Lifecycle Hooks
Spring provides hooks to execute code when beans are initialized or destroyed.
import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Service public class DatabaseConnectionService { @PostConstruct public void init() { // Called after bean creation and dependency injection System.out.println("Initializing database connection pool..."); } @PreDestroy public void cleanup() { // Called before bean is destroyed (application shutdown) System.out.println("Closing database connections..."); } @PostConstruct public void validateConfig() { // Multiple @PostConstruct methods allowed System.out.println("Validating configuration..."); } }
Conditional Beans (@Conditional)
Spring allows conditional bean creation based on environment, classpath, properties, or custom logic.
@Configuration public class ConditionalConfig { @Bean @ConditionalOnProperty(name = "cache.enabled", havingValue = "true") public CacheService cacheService() { return new RedisCacheService(); } @Bean @ConditionalOnMissingBean public DataSource dataSource() { return new HikariDataSource(); } @Bean @ConditionalOnClass(name = "org.postgresql.Driver") public PostgreSQLDialect postgresDialect() { return new PostgreSQLDialect(); } @Bean @Profile("dev") public DevService devService() { return new DevService(); } @Bean @Profile("prod") public ProdService prodService() { return new ProdService(); } }
Knowledge Check
Ready to test your understanding of 7. Spring Beans & Application Context?