Java Notes
Deep dive into Spring Core Container - BeanFactory, ApplicationContext, bean lifecycle, bean scopes, profiles, and Spring Expression Language (SpEL).
The IoC Container
The Spring IoC container is the core of the Spring Framework. It creates objects, wires them together, configures them, and manages their complete lifecycle.
Container Types
| Container | Interface | Description |
|---|---|---|
| BeanFactory | BeanFactory | Basic container, lazy initialization |
| ApplicationContext | ApplicationContext | Advanced container, eager init, events |
// BeanFactory (basic — rarely used directly)
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
// ApplicationContext (standard — always use this)
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
ApplicationContext ctx2 = new ClassPathXmlApplicationContext("beans.xml");
ApplicationContext ctx3 = new FileSystemXmlApplicationContext("/path/beans.xml");ApplicationContext Extra Features
| Feature | Description |
|---|---|
| Internationalization | MessageSource for i18n |
| Event Publishing | ApplicationEvent system |
| Resource Loading | Access files, URLs, classpath |
| AOP Integration | Auto-proxy creation |
| Eager Initialization | Catches config errors at startup |
Bean Scopes
| Scope | Description | Lifecycle |
|---|---|---|
| singleton | One instance per container (default) | Container lifetime |
| prototype | New instance per request | Created each time, not destroyed by container |
| request | One per HTTP request | Request lifetime |
| session | One per HTTP session | Session lifetime |
| application | One per ServletContext | Application lifetime |
@Component
@Scope("singleton") // Default — one instance shared
public class ConfigService { }
@Component
@Scope("prototype") // New instance every time
public class ShoppingCart { }
@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestLogger { }
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserSession { }Singleton vs Prototype
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
// Singleton — same instance
ConfigService c1 = ctx.getBean(ConfigService.class);
ConfigService c2 = ctx.getBean(ConfigService.class);
System.out.println(c1 == c2); // true
// Prototype — different instances
ShoppingCart s1 = ctx.getBean(ShoppingCart.class);
ShoppingCart s2 = ctx.getBean(ShoppingCart.class);
System.out.println(s1 == s2); // falsetrue false
Bean Configuration Methods
Method 1: Component Scanning
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig { }
@Service
public class UserService { } // Auto-discoveredMethod 2: @Bean Methods
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean(name = "emailSender")
@Profile("production")
public EmailService emailService() {
return new SmtpEmailService();
}
@Bean
@ConditionalOnProperty(name = "cache.enabled", havingValue = "true")
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("users", "products");
}
}Method 3: XML (Legacy)
<bean id="userService" class="com.example.UserService">
<property name="repository" ref="userRepository" />
<property name="maxRetries" value="3" />
</bean>Profiles
@Configuration
public class DataSourceConfig {
@Bean
@Profile("dev")
public DataSource devDataSource() {
// H2 in-memory database for development
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.build();
}
@Bean
@Profile("prod")
public DataSource prodDataSource() {
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl("jdbc:mysql://prod-server:3306/mydb");
return ds;
}
}
// Activate profile
// java -Dspring.profiles.active=prod -jar app.jar
// Or: context.getEnvironment().setActiveProfiles("prod");Spring Expression Language (SpEL)
Property Sources
@Configuration
@PropertySource("classpath:application.properties")
@PropertySource("classpath:database.properties")
public class AppConfig {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl(env.getProperty("db.url"));
ds.setUsername(env.getProperty("db.username"));
ds.setPassword(env.getProperty("db.password"));
return ds;
}
}application.properties:
app.name=MyApplication
app.timeout=30
db.url=jdbc:mysql://localhost:3306/mydb
db.username=root
db.password=secretBeanPostProcessor
Allows custom modification of beans before/after initialization:
@Component
public class LoggingBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if (bean.getClass().isAnnotationPresent(Service.class)) {
System.out.println("Initializing service: " + beanName);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
// Could create proxies here (AOP does this)
return bean;
}
}Interview Key Points
- ApplicationContext is preferred over BeanFactory (eager init, events, i18n)
- Default scope is singleton — ONE instance per container
- Bean lifecycle: Instantiate → DI → Aware → PostProcessor → Init → Ready → Destroy
@PostConstructruns after DI;@PreDestroyruns before destruction- Prototype beans are NOT destroyed by the container
- Profiles allow environment-specific configuration
- SpEL (
#{expr}) evaluates expressions;${prop}reads properties - BeanPostProcessor can modify any bean (AOP uses this internally)
Summary
In this chapter, we learned about Spring Core Container in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Spring Core Container.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, spring, framework, core
Related Java Master Course Topics