Spring_boot__1750078380
Spring_boot__1750078380
● ✅
○ Health checks, metrics, externalized config via Actuator
● ✅
Reduced Boilerplate Code
● ✅
Easy Dependency Management
Seamless Integration with Spring Ecosystem
○ Compatible with Spring Data JPA, Spring Security,
✅
Spring WebFlux, Spring Batch
● Flexible Configuration
○ Supports application.properties and
application.yml
● ✅ Community and Ecosystem Support
🔹 E-Commerce Platforms
🔹 Banking & Financial Services
●
🔹 Healthcare Systems
●
Language Support:
✅ Groovy
●
Learning Curve Steeper for beginners Easier and quicker to get started
➢ 2. Getting Started
2.1. Setting up Spring Boot Project (Spring Initializr, Maven, Gradle)
2.2. Project Structure Overview
2.3. Application Entry Point (@SpringBootApplication)
2.4. Running the Application
➢ 3. Core Concepts
3.1. Spring Boot Annotations
1. @SpringBootApplication
2. @Component, @Service, @Repository, @Controller, @RestController
3. @Autowired, @Qualifier
4. @Configuration, @Bean
3.2. Dependency Injection (DI)
3.3. Inversion of Control (IoC)
➢ 4. Configuration
4.1. application.properties vs application.yml
4.2. External Configuration (env vars, CLI args)
4.3. Profiles (@Profile)
4.4. Property Injection: @Value, @ConfigurationProperties
➢ 7. Data Access
7.1. Spring Data JPA
1. Entity Classes (@Entity)
2. Repositories (JpaRepository, CrudRepository)
3. Custom Queries (@Query)
4. Pagination and Sorting
7.2. JDBC with Spring Boot
7.3. MongoDB / NoSQL
7.4. Transactions (@Transactional)
➢ 8. Database Configuration
8.1. H2 In-Memory Database
8.2. MySQL/PostgreSQL setup
8.3. Connection Pooling (HikariCP)
8.4. Schema Initialization (schema.sql, data.sql)
➢ 9. Validation
9.1. Bean Validation (javax.validation)
9.2. Using @Valid, @Validated
9.3. Custom Validators
➢ 10. Security
10.1. Spring Security Basics
10.2. Authentication and Authorization
10.3. Password Encoding
10.4. JWT Token-based Security
10.5. Role-Based Access Control
➢ 11. Testing
11.1. Unit Testing with JUnit
11.2. Mocking with Mockito
11.3. Integration Testing
11.4. Web Layer Testing (@WebMvcTest)
11.5. Data Layer Testing (@DataJpaTest)
➢ 12. Logging
12.1. SLF4J and Logback
12.2. Configuring Log Levels
12.3. External Log Configuration
➢ 18. Messaging
18.1. RabbitMQ
18.2. Kafka
18.3. JMS Integration
2. Getting Started
2.1. Setting up Spring Boot Project (Spring Initializr,
Maven, Gradle)
https://start.spring.io/
2.2. Project Structure Overview
2.3. Application Entry Point (@SpringBootApplication)
2.4. Running the Application
3. Core Concepts
1. @SpringBootApplication
Declaration
@SpringBootApplication
SpringApplication.run(MyApplication.class, args);
}
1. @Component
Definition
// Business logic
Use Case
Used when the class doesn't clearly fall into service, repository, or controller layers.
2. @Service
Definition
@Service
// Business logic
}
Use Case
3. @Repository
Definition
// Save to DB
}
Use Case
4. @Controller
Definition
@Controller is used to define web layer classes in Spring MVC. It is used for rendering
views (HTML) with model data.
@Controller
@GetMapping("/")
model.addAttribute("message", "Welcome");
}
Use Case
Used when working with traditional web applications (Thymeleaf, JSP, etc.)
5. @RestController
Definition
@RestController
@GetMapping("/users")
return userService.getAll();
}
Use Case
Summary Table
3. @Autowired, @Qualifier
@Autowired is used to automatically wire dependencies.
1. @Autowired
Definition
@Component
@Autowired
● On fields
● On constructors
● On setter methods
@Service
@Autowired
this.paymentService = paymentService;
}
2. @Qualifier
Definition
@Component("dieselEngine")
@Component("petrolEngine")
public class PetrolEngine implements Engine { }
@Service
@Autowired
@Qualifier("dieselEngine")
Use Case
4. @Configuration, @Bean
1. @Configuration
Definition
@Configuration
@Configuration
2. @Bean
Definition
@Bean
@Configuration
@Bean
}
@Bean
}
3.2. Dependency Injection (DI)
Dependency Injection is a programming technique where an object receives its dependencies
from an external source rather than creating them internally.
Field Injection Dependencies are injected directly into Quick but less recommended
fields using @Autowired. for testing
@Autowired
this.paymentService = paymentService;
}
paymentService.processPayment();
}
Here:
Annotation Purpose
Inversion of Control (IoC) is a design principle in which the control of object creation and
dependency resolution is transferred from the program (developer) to a framework or
container.
Overview
● application.properties vs application.yml
Example: application.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=root
spring.datasource.password=pass
Example: application.yml
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/db
username: root
password: pass
4.2 External Configuration
export SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/db
Spring Profiles allow you to define environment-specific configurations (e.g., dev, test, prod).
○ application-dev.properties
○ application-prod.yml
○ Application.properties:
spring.profiles.active=dev
○ Or via CLI:
@Configuration
@Profile("dev")
@Bean
}
}
@Configuration
@Profile("prod")
@Bean
}
1. @Value Annotation
@Component
@Value("${server.port}")
2. @ConfigurationProperties Annotation
YAML Example
app:
name: MyApp
version: 1.0
@Component
@ConfigurationProperties(prefix = "app")
Comparison Table
Key Benefits
Example pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
5.2.1 spring-boot-starter-web
Used to build web applications and RESTful services using Spring MVC.
Includes:
● Spring MVC
@RestController
@GetMapping("/hello")
}
5.2.2 spring-boot-starter-data-jpa
Used to enable Spring Data JPA for data access with relational databases.
Includes:
● Hibernate
● Spring ORM
@Entity
@Id @GeneratedValue
5.2.3 spring-boot-starter-security
Includes:
● Spring Security
Example Use Case:
@Configuration
@Override
http.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin();
}
5.2.4 spring-boot-starter-test
Includes:
● JUnit 5
● Mockito
● Spring Test
● AssertJ
@SpringBootTest
@Autowired
private MyService myService;
@Test
void testLogic() {
assertEquals("expected", myService.doSomething());
}
Starter Purpose
Spring Boot supports full-stack web development using Spring MVC, allowing you to build
RESTful APIs and web applications easily. This section covers core web development concepts
such as REST controllers, request handling, exception management, and content negotiation.
Example
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "John Doe");
}
}
@GetMapping("/find")
public String findUser(@RequestParam String role) {
return "Finding user with role: " + role;
}
Example
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.findById(id);
if (user == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
return ResponseEntity.ok(user);
}
Global exception handling using @ControllerAdvice and specific error response logic using
@ExceptionHandler.
Example
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}
Example
@GetMapping(value = "/info", produces = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public User getInfo() {
return new User(1L, "Alice");
}
Overview
Spring Boot simplifies data access by providing integration with various data sources like
relational databases (via JPA and JDBC) and NoSQL databases (e.g., MongoDB). It also
supports robust transaction management.
Example
@Entity
@Id @GeneratedValue
Spring Data provides interfaces for CRUD operations without boilerplate code.
Example
}
3 Custom Queries (@Query)
Example
Example
Example
@Repository
@Autowired
Example
@Document
@Id
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
7.4 Transactions (@Transactional)
Ensures atomicity for multiple database operations.
Example
@Service
@Autowired
@Transactional
userRepository.save(user);
// Additional DB operations
}
Overview
Spring Boot offers seamless integration with relational databases such as H2, MySQL,
PostgreSQL, and supports configuration for connection pooling and schema initialization
through simple properties or SQL files.
8.1 H2 In-Memory Database
The H2 database is an in-memory relational database ideal for development and testing. It runs
in memory and is destroyed when the application stops.
Add Dependency
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Configure (application.properties)
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
H2 Console
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
PostgreSQL Configuration
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=postgres
spring.datasource.password=your_password
8.3 Connection Pooling (HikariCP)
Spring Boot uses HikariCP as the default connection pool for better performance.
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=SpringBootHikariCP
Usage
Example: schema.sql
name VARCHAR(100)
);
Example: data.sql
INSERT INTO users (name) VALUES ('John Doe'), ('Alice');
Overview
Spring Boot supports bean validation using JSR-380 (Jakarta Bean Validation /
javax.validation). It allows automatic input validation for REST APIs and form data using
annotations like @NotNull, @Email, and more. Validation can be enhanced using @Valid,
@Validated, and custom validators.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Annotation Description
Example
@NotBlank
@Min(18)
}
9.2 Using @Valid and @Validated
@Valid
@RestController
@RequestMapping("/users")
@PostMapping
}
Spring will automatically return a 400 Bad Request if validation fails, along with error
messages.
@Validated
@Validated
@Service
@Constraint(validatedBy = UsernameValidator.class)
@Target({ FIELD })
@Retention(RUNTIME)
public class UsernameValidator implements ConstraintValidator<ValidUsername, String>
{
@Override
public class User {
@ValidUsername
Overview
Spring Boot integrates Spring Security, a powerful and customizable authentication and
access-control framework. It provides robust security for web applications, REST APIs, and
microservices.
Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
By default, Spring Security:
@Configuration
@EnableWebSecurity
@Bean
http
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
)
return http.build();
}
@Bean
UserDetails user =
User.withUsername("user").password("{noop}1234").roles("USER").build();
UserDetails admin =
User.withUsername("admin").password("{noop}admin123").roles("ADMIN").build();
}
@Bean
JWT Flow
@RestController
@PostMapping("/login")
return jwtService.generateToken(request.getUsername());
}
}
Example
@GetMapping("/admin/dashboard")
@PreAuthorize("hasRole('ADMIN')")
@EnableMethodSecurity
Overview
Spring Boot provides first-class support for testing through JUnit, Mockito, and Spring
TestContext Framework. It enables testing of individual components (unit tests), interactions
(mocking), and full application context (integration testing).
Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Example
class CalculatorService {
return a + b;
}
class CalculatorServiceTest {
@Test
void testAdd() {
}
Example
@Service
class OrderService {
return paymentService.pay();
}
class OrderServiceTest {
@BeforeEach
void init() {
MockitoAnnotations.openMocks(this);
}
@Test
void testPlaceOrder() {
when(paymentService.pay()).thenReturn(true);
assertTrue(orderService.placeOrder());
}
Example
@SpringBootTest
class UserServiceIntegrationTest {
@Test
void testFindUser() {
assertNotNull(user);
}
Example
@WebMvcTest(UserController.class)
class UserControllerTest {
@Test
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());
}
It auto-configures Spring MVC infrastructure and can mock service beans using
@MockBean.
11.5 Data Layer Testing (@DataJpaTest)
Used to test repository layer with in-memory database and only JPA components.
Example
@DataJpaTest
class UserRepositoryTest {
@Test
void testSaveUser() {
assertNotNull(saved.getId());
}
Uses H2 in-memory database by default and rolls back transactions after each test.
Overview
Spring Boot uses SLF4J (Simple Logging Facade for Java) as a logging API and Logback as
the default logging implementation. Logging helps monitor application behavior, track errors,
and audit key events.
12.1 SLF4J and Logback
SLF4J
● A facade that allows switching between logging frameworks like Logback, Log4j, etc.
Basic Usage
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestController
@GetMapping("/test")
logger.warn("WARN log");
logger.error("ERROR log");
}
}
12.2 Configuring Log Levels
Spring Boot allows configuring log levels in application.properties or
application.yml.
Example: application.properties
logging.level.root=INFO
logging.level.com.example.demo=DEBUG
logging.file.name=app.log
Log Levels
Steps:
2. Use Spring profile-specific logging, log rotation, custom patterns, etc.
Example: logback-spring.xml
<configuration>
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
</rollingPolicy>
<encoder>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="FILE"/>
</root>
</configuration>
You can also use environment variables and Spring profiles for flexible logging configurations.
Spring Boot Actuator provides built-in monitoring and management endpoints to inspect
application health, metrics, and environment details. It is essential for observing applications in
production environments.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
management.endpoints.web.exposure.include=*
By default, only limited endpoints like /health and /info are exposed.
Endpoint Description
management.endpoints.web.exposure.include=info
info.app.name=MyApp
info.app.version=1.0
@Component
this.counter = registry.counter("custom.visit.counter");
}
counter.increment();
}
Prometheus Setup
Add dependency:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
application.properties:
management.endpoints.web.exposure.include=prometheus
management.metrics.export.prometheus.enabled=true
/actuator/prometheus
Grafana Integration
Overview
Spring Boot provides a default error handling mechanism and allows full customization via
exception handlers, error pages, and controller advice. Proper error handling ensures a better
user experience and easier debugging.
"timestamp": "2025-06-14T12:30:00.000+00:00",
"status": 404,
"path": "/api/users/100"
Examples:
Example:
@ControllerAdvice
}
@ExceptionHandler(Exception.class)
}
This ensures consistent and customizable error responses across the application.
Best Practices
Overview
Spring Boot Developer Tools (DevTools) enhance the development experience by enabling
automatic restarts, live reload, and additional features like runtime property override and
template caching disablement.
Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
In Gradle:
developmentOnly("org.springframework.boot:spring-boot-devtools")
Benefits:
Example
spring.devtools.restart.exclude=static/**,public/**
Steps to Enable:
Configuration (optional)
spring.devtools.livereload.enabled=true
Other Features
Overview
✅ @EnableCaching
Enable caching in your main class:
@SpringBootApplication
@EnableCaching
✅ @Cacheable
Marks a method’s return value to be cached. The result is stored the first time and reused
for subsequent calls with the same parameters.
@Cacheable("products")
return productRepository.findById(id).orElse(null);
On subsequent calls with same id, value is fetched from the cache.
✅ @CacheEvict
Removes an entry from the cache.
productRepository.deleteById(id);
➤ Add dependency:
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<config>
<cache alias="products">
<heap>1000</heap>
</cache>
</config>
➤ Add dependency:
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
➤ Configuration (application.properties):
spring.cache.type=caffeine
spring.cache.caffeine.spec=maximumSize=1000,expireAfterAccess=5m
Redis (Distributed cache)
➤ Add dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
➤ Configuration:
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
Overview
Spring Boot simplifies the execution of background and periodic tasks through annotations like
@Scheduled and @Async. These features enable automation, performance optimization, and
non-blocking operations.
17.1 Scheduling Tasks (@Scheduled)
@Scheduled allows you to run methods at fixed intervals or specific times.
✅ Enable Scheduling
@SpringBootApplication
@EnableScheduling
✅ Using @Scheduled
@Component
}
}
}
fixedRate: Runs task at regular intervals.
@EnableAsync
✅ Using @Async
@Service
@Async
// Simulate delay
try {
Thread.sleep(3000);
} catch (InterruptedException ignored) {}
}
@Autowired
@GetMapping("/notify")
emailService.sendEmail("[email protected]");
}
Overview
Spring Boot offers powerful support for message-driven architecture using brokers like
RabbitMQ, Apache Kafka, and JMS (Java Message Service). Messaging enables
asynchronous communication, event-driven processing, and microservice decoupling.
18.1 RabbitMQ
RabbitMQ is a message broker that supports AMQP for reliable, asynchronous message
delivery.
✅ Add Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
✅ Configuration (application.properties)
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
✅ Producer Example
@Service
@Autowired
rabbitTemplate.convertAndSend("myQueue", message);
}
✅ Consumer Example
@Component
@RabbitListener(queues = "myQueue")
}
✅ Add Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka</artifactId>
</dependency>
✅ Configuration (application.properties)
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=my-group
spring.kafka.consumer.auto-offset-reset=earliest
✅ Producer Example
@Service
@Autowired
kafkaTemplate.send("myTopic", message);
}
✅ Consumer Example
@Component
}
✅ Add Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-artemis</artifactId>
</dependency>
✅ Configuration
spring.artemis.broker-url=tcp://localhost:61616
spring.artemis.user=admin
spring.artemis.password=admin
✅ Producer Example
@Service
@Autowired
jmsTemplate.convertAndSend("queue.sample", msg);
}
✅ Consumer Example
@Component
@JmsListener(destination = "queue.sample")
}
Overview
Spring Boot provides built-in support for handling file uploads using MultipartFile, and
allows secure file storage and download through REST APIs. These features are essential for
applications like user portals, document systems, and image uploads.
@RequestMapping("/files")
@PostMapping("/upload")
Files.createDirectories(path.getParent());
Files.write(path, file.getBytes());
}
if (!resource.exists()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
✅ Security Tip
Always validate:
spring.servlet.multipart.max-request-size=10MB
Overview
Spring Boot simplifies frontend integration by allowing you to serve static content, use
server-side templating engines like Thymeleaf, and enable CORS for cross-origin requests from
frontend frameworks like Angular, React, or Vue.
src/main/resources/static/
src/main/resources/public/
src/main/resources/resources/
✅ Example
src/main/resources/static/index.html
Accessible via: http://localhost:8080/index.html
/static/js/app.js
/static/css/style.css
✅ Add Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
✅ Controller
@Controller
@GetMapping("/home")
return "home";
}
✅ Template: src/main/resources/templates/home.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Home</title></head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
@Override
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:4200")
}
}
✅ Enable CORS at Controller Level
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api")
@GetMapping("/products")
}
Overview
Spring Boot simplifies application deployment with flexible options such as executable
JARs/WARs, Docker containers, cloud deployment, and CI/CD integration for automated
delivery.
<packaging>jar</packaging>
Extend SpringBootServletInitializer
@SpringBootApplication
@Override
protected SpringApplicationBuilder
configure(SpringApplicationBuilder builder) {
return builder.sources(MyApp.class);
}
✅ Create Dockerfile
FROM openjdk:21
COPY target/myapp.jar app.jar
✅ Run Container
docker run -p 8080:8080 myapp
● Example:
eb init
eb create my-spring-env
eb deploy
● Deploy using:
runtime: java
env: standard
Deploy:
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
uses: actions/setup-java@v3
with:
java-version: '21'
- name: Build
Overview
Advanced Spring Boot features enable the development of resilient, scalable, and modular
applications using microservices, event-driven architecture, and custom starters.
A set of tools to support microservice patterns: configuration, discovery, routing, load balancing,
and resilience.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2023.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
● Eureka Server:
@EnableEurekaServer
@SpringBootApplication
Eureka Client:
@EnableEurekaClient
@SpringBootApplication
Add dependency:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
@SpringBootApplication
Config in application.yml:
spring:
cloud:
gateway:
routes:
- id: product_route
uri: http://localhost:8081
predicates:
- Path=/products/**
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
</dependency>
Config Server:
@EnableConfigServer
@SpringBootApplication
public class ConfigServerApp { ... }
application.yml:
spring:
cloud:
config:
server:
git:
uri: https://github.com/my-org/config-repo
Client:
spring:
config:
import: optional:configserver:http://localhost:8888
✅ Publish Event
@Autowired
private ApplicationEventPublisher publisher;
✅ Listen to Event
@Component
public class UserEventListener {
@EventListener
public void handleUserCreated(UserCreatedEvent event) {
System.out.println("User created: " + event.getEmail());
}
}
✅ Steps:
1. Create a separate module (e.g., my-spring-boot-starter)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.autoconfig.MyAutoConfiguration
4. Example Auto-Configuration:
@Configuration
public class MyAutoConfiguration {
@Bean
public MyService myService() {
return new MyService();
}
}