Spring Framework: Concepts and Examples
1. What is Spring Framework?
Spring is an open-source Java framework that provides comprehensive infrastructure support for developing enterprise applications. It is lightweight and supports modularity, allowing developers to build robust applications with loosely coupled components.
2. History of Spring
- 2002: Introduced by Rod Johnson as part of his book “Expert One-on-One J2EE Design and Development.”
- 2003: First version released as Spring Framework.
- 2004: Official release of Spring 1.0.
- Since then, Spring has evolved to support modern practices like microservices, cloud computing, and reactive programming.
3. Key Concepts
Dependency Injection (DI)
Dependency Injection is a design pattern used to achieve Inversion of Control (IoC). It decouples components by providing their dependencies from an external source rather than allowing the component to create them.
Inversion of Control (IoC)
IoC is a principle where the control of object creation and dependency management is shifted from the application to a container (like the Spring IoC container).
Spring and JEE
Spring complements Java EE (JEE) by providing additional features and simplifying enterprise development. It offers alternatives to cumbersome Java EE components like EJBs and integrates seamlessly with Java EE technologies.
4. Spring Modules
- Core Container: Includes
Beans,Context, andCoremodules. - AOP (Aspect-Oriented Programming): Adds cross-cutting concerns like logging, security.
- Data Access/Integration: Modules like
JDBC,ORM, andTransactions. - Web: Supports web applications with modules like
Spring MVC. - Spring Boot: Simplifies configuration for standalone applications.
- Spring Security: Provides authentication and authorization mechanisms.
- Spring Batch: Handles batch processing tasks such as ETL.
- Spring Cloud: Simplifies building microservices and distributed systems.
5. IoC Container
Steps in IoC Lifecycle:
- Instantiate container (e.g.,
ClassPathXmlApplicationContext). - Define bean configuration (XML or annotations).
- Container manages the lifecycle and dependency injection.
IoC Lifecycle Phases:
- Bean instantiation.
- Dependency injection.
- Post-initialization (
@PostConstructor custom init methods). - Bean destruction (
@PreDestroyor custom destroy methods).
6. Application Context and Types
ApplicationContext is the central interface in Spring for managing the application lifecycle.
Types of ApplicationContext:
ClassPathXmlApplicationContext: Loads configuration from the classpath.FileSystemXmlApplicationContext: Loads configuration from the file system.AnnotationConfigApplicationContext: Loads configuration from Java-based annotations.
7. Dependency Injection in IoC
Types of DI:
- Constructor Injection:
<bean id="example" class="com.example.Class">
<constructor-arg name="dependency" ref="dependencyBean" />
</bean>
- Setter Injection:
<bean id="example" class="com.example.Class">
<property name="dependency" ref="dependencyBean" />
</bean>
- Field Injection (with annotations):
@Autowired private Dependency dependency;
Supported Data Types:
- Primitive types (
int,String, etc.). - Collection types (
List,Set,Map).
8. Lifecycle Methods
Spring provides lifecycle callbacks for beans:
- Initialization:
@PostConstruct<bean init-method="initMethod">(XML).
- Destruction:
@PreDestroy<bean destroy-method="destroyMethod">(XML).
Example:
public class MyBean {
@PostConstruct
public void init() {
System.out.println("Bean is initialized");
}
@PreDestroy
public void destroy() {
System.out.println("Bean is destroyed");
}
}
9. Autowiring in Spring
Types of Autowiring:
- ByType: Automatically wires beans by matching types.
<bean id="example" autowire="byType" />
- ByName: Wires by matching property names with bean IDs.
<bean id="example" autowire="byName" />
- Constructor: Wires dependencies using constructor arguments.
- Annotations (
@Autowired):- Automatically wires beans by type.
- Use
@Qualifierfor precise control.
@Autowired @Qualifier("specificBean") private Dependency dependency;
10. Bean Scopes
Supported Scopes:
singleton(Default): A single instance per Spring container.prototype: A new instance for each request.request,session,globalSession(for web apps).
Example:
@Component
@Scope("prototype")
public class PrototypeBean {}
11. Qualifier and Primary
Qualifier:
Specifies which bean to use when multiple candidates exist.
@Autowired
@Qualifier("specificBean")
private Dependency dependency;
Primary:
Defines the default bean.
@Primary
@Bean
public UserService defaultUserService() {
return new DefaultUserService();
}
12. Examples
Basic XML Configuration:
<beans>
<bean id="example" class="com.example.Class">
<property name="dependency" ref="dependencyBean" />
</bean>
</beans>
Annotation-Based Configuration:
@Configuration
@ComponentScan("com.example")
public class AppConfig {
@Bean
public Dependency dependencyBean() {
return new Dependency();
}
}
Spring Boot Application Example:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}