Spring Core Guide Lyst1744875567054
Spring Core Guide Lyst1744875567054
class DatabaseService {
public void connect() {
System.out.println("Database connected!");
}
}
class Application {
private DatabaseService databaseService;
public Application() {
databaseService = new DatabaseService(); // Tightly coupled
}
Types of DI
1. Constructor Injection
2. Setter Injection
3. Field Injection
1. Constructor Injection
In Constructor Injection, the dependency is provided through the class
constructor.
Example:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
// Dependency
@Component
class DatabaseService {
public void connect() {
System.out.println("Database connected via Constructor Injection!");
}
// Dependent class
@Component
class Application {
private final DatabaseService databaseService;
// Constructor Injection
@Autowired
public Application(DatabaseService databaseService) {
this.databaseService = databaseService;
}
// Main Class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
var context = SpringApplication.run(Main.class, args);
var app = context.getBean(Application.class);
app.start();
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
2. Setter Injection
In Setter Injection, the dependency is provided through a setter method.
Example:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
// Dependency
@Component
class DatabaseService {
public void connect() {
System.out.println("Database connected via Setter Injection!");
}
}
// Dependent class
@Component
class Application {
private DatabaseService databaseService;
// Setter Injection
@Autowired
public void setDatabaseService(DatabaseService databaseService) {
this.databaseService = databaseService;
}
// Main Class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
var context = SpringApplication.run(Main.class, args);
var app = context.getBean(Application.class);
app.start();
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
Example:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
// Dependency
@Component
class DatabaseService {
public void connect() {
System.out.println("Database connected via Field Injection!");
}
}
// Dependent class
@Component
class Application {
@Autowired
private DatabaseService databaseService; // Field Injection
// Main Class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
var context = SpringApplication.run(Main.class, args);
var app = context.getBean(Application.class);
Note: Field Injection is not directly supported in XML configuration. You must
use either constructor or setter injection in XML.
Risk of incomplete
Setter Injection Flexible for optional dependencies. initialization if
dependencies are not set.
Best Practices
Use Constructor Injection for mandatory dependencies (preferred in most
cases).
Key Points
1. XML Configuration is less popular now but is still useful for legacy projects.
1. XML Configuration
Add the following to your beans.xml file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springfr
amework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springf
ramework.org/schema/context/spring-context.xsd">
Here:
Spring will scan the package com.example and all its sub-packages.
2. Annotated Classes
Annotate your classes with the appropriate Spring annotations:
Example:
import org.springframework.stereotype.Component;
@Component
public class DatabaseService {
public void connect() {
System.out.println("Database connected!");
}
}
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Application {
private final DatabaseService databaseService;
@Autowired
public Application(DatabaseService databaseService) {
this.databaseService = databaseService;
}
3. Main Class
Load the application context from the XML configuration and use the beans:
Key Points
1. Base Package:
2. Multiple Packages:
<context:component-scan base-package="com.example,com.othe
r"/>
3. Filter Components:
Bean Lifecycle
The Spring Bean Lifecycle describes the process that a Spring-managed bean
goes through from creation to destruction. Spring provides a powerful way to
manage this lifecycle with hooks and callback methods.
Lifecycle Phases
1. Bean Instantiation:
The container creates an instance of the bean using the no-argument
constructor or a static factory method.
2. Populate Properties:
Spring injects dependencies into the bean, either via constructor, setter
methods, or field injection.
4. Pre-Initialization (BeanPostProcessor):
Before the initialization callbacks, BeanPostProcessor methods are invoked for
any custom processing.
5. Initialization:
8. Destruction:
When the application shuts down, the container destroys the bean, calling
methods annotated with @PreDestroy or DisposableBean 's destroy() method.
XML Configuration
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-be
ans.xsd">
Java Class
package com.example;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public LifecycleBean() {
System.out.println("1. Bean Instantiation");
}
@PostConstruct
public void postConstruct() {
System.out.println("2. @PostConstruct - Called after dependencies ar
e injected.");
}
@Override
public void afterPropertiesSet() {
System.out.println("3. InitializingBean's afterPropertiesSet() - Custom i
nitialization logic here.");
}
@PreDestroy
public void preDestroy() {
System.out.println("5. @PreDestroy - Cleanup before destruction.");
}
@Override
public void destroy() {
System.out.println("6. DisposableBean's destroy() - Additional cleanup
logic here.");
Example:
package com.example;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanNa
me) throws BeansException {
System.out.println("After Initialization: " + beanName);
return bean;
}
}
markdown
Copy code
1. Bean Instantiation
Before Initialization: exampleBean
2. @PostConstruct - Called after dependencies are injected.
3. InitializingBean's afterPropertiesSet() - Custom initialization logic here.
4. Custom init-method - Declared in XML or Java config.
After Initialization: exampleBean
...
5. @PreDestroy - Cleanup before destruction.
6. DisposableBean's destroy() - Additional cleanup logic here.
7. Custom destroy-method - Declared in XML or Java config.
Cleanup logic
Destruction @PreDestroy , destroy() , destroy-method before bean
removal
Example:
@Component
@Scope("singleton") // Optional as it's the default scope
public class SingletonBean {
public SingletonBean() {
System.out.println("SingletonBean instance created!");
}
}
2. Prototype
Description: A new instance of the bean is created every time it is
requested.
Use Case: Stateful beans or beans requiring a unique instance for every
use.
Example:
@Component
@Scope("prototype")
public class PrototypeBean {
public PrototypeBean() {
System.out.println("PrototypeBean instance created!");
}
}
Output:
If this bean is retrieved multiple times:
Example:
@Component
@Scope("request")
public class RequestBean {
public RequestBean() {
System.out.println("RequestBean instance created!");
}
}
How to use:
This scope works in a Spring MVC or Spring Web application. Each HTTP
request will create a new RequestBean .
Example:
@Component
@Scope("session")
Example:
@Component
@Scope("application")
public class ApplicationBean {
public ApplicationBean() {
System.out.println("ApplicationBean instance created!");
}
}
Example:
@Component
xml
Copy code
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
Scope