Thursday, 19 June 2025

Spring Boot Project Setup

 

1. Spring Boot Project Setup (using Spring Initializer)

Go to 👉 https://start.spring.io and generate a project with:

  • Project: Maven

  • Language: Java

  • Spring Boot: 3.2 (or latest stable)

  • Dependencies:

    • Spring Web

    • Spring Data JPA

    • H2 Database

    • Spring Boot Actuator

Click “Generate”, then unzip and open it in IntelliJ IDEA, VS Code, or Eclipse.


📁 2. Project Structure Breakdown


customer-service/ ├── src/main/java/com/example/customer │ ├── CustomerServiceApplication.java <-- Main app class │ ├── controller/CustomerController.java <-- REST API logic │ ├── model/Customer.java <-- Data structure (Entity) │ └── repository/CustomerRepository.java <-- DB operations ├── src/main/resources │ └── application.yml <-- Configuration file ├── pom.xml <-- Maven build file

3. Step-by-Step File Explanation


📌 CustomerServiceApplication.java


@SpringBootApplication public class CustomerServiceApplication { public static void main(String[] args) { SpringApplication.run(CustomerServiceApplication.class, args); } }

🔹 Explanation:

  • @SpringBootApplication = Combines 3 annotations:

    • @Configuration (declares beans)

    • @EnableAutoConfiguration (auto sets up Spring features)

    • @ComponentScan (scans your code for components like @Controller)

  • main() = the entry point. Runs the app like a regular Java program.


📌 Customer.java (inside model/)


@Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // Getters & setters }

🔹 Explanation:

  • This is a Java class (POJO) that represents a table in the database.

  • @Entity tells Spring it's a database table.

  • @Id = primary key, @GeneratedValue = auto-increment.

  • When the app runs, Spring Boot creates a table named customer in the H2 DB.


📌 CustomerRepository.java (inside repository/)


public interface CustomerRepository extends JpaRepository<Customer, Long> {}

🔹 Explanation:

  • This is an interface — no code inside, yet it works!

  • JpaRepository provides built-in methods like:

    • findAll()

    • save()

    • deleteById()

    • findById()

  • Spring will generate the implementation automatically.


📌 CustomerController.java (inside controller/)


@RestController @RequestMapping("/api/customers") public class CustomerController { @Autowired private CustomerRepository repository; @GetMapping public List<Customer> getAll() { return repository.findAll(); } @PostMapping public Customer create(@RequestBody Customer customer) { return repository.save(customer); } }

🔹 Explanation:

  • @RestController = this class handles HTTP requests and returns data.

  • @RequestMapping("/api/customers") = base path for all endpoints.

  • @Autowired = Spring injects the repository automatically.

  • @GetMapping = handles GET /api/customers (return all customers).

  • @PostMapping = handles POST /api/customers (create a new customer).

  • @RequestBody = converts incoming JSON to a Customer object.


📌 application.yml


server: port: 8080 spring: datasource: url: jdbc:h2:mem:testdb driverClassName: org.h2.Driver username: sa password: jpa: hibernate: ddl-auto: update show-sql: true management: endpoints: web: exposure: include: "*"

🔹 Explanation:

  • Tells Spring Boot to:

    • Use port 8080

    • Use in-memory H2 DB

    • Automatically update the schema from entities

    • Expose health, metrics, and other actuator endpoints


▶️ 4. Running the App

  1. Run CustomerServiceApplication.java (as Java Application)

  2. Test in browser or with curl/Postman:


curl http://localhost:8080/api/customers

🐳 5. Dockerizing the App

Step-by-step:

🐘 Build the project


mvn clean package

This creates a file like target/customer-service-0.0.1-SNAPSHOT.jar.


🐳 Dockerfile


FROM openjdk:17-jdk-slim WORKDIR /app COPY target/*.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar"]

🛠 Build and Run Docker


docker build -t customer-service . docker run -p 8080:8080 customer-service

Now your app is running in a container!


🚀 6. CI/CD with GitHub Actions

Here’s a simple GitHub Actions pipeline:

.github/workflows/build.yml


name: Build Spring Boot App on: push: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-java@v3 with: java-version: '17' distribution: 'temurin' - name: Build with Maven run: mvn clean package - name: Build Docker image run: docker build -t my-customer-service . # Optionally, push to DockerHub or deploy to Kubernetes

🛠️ 7. Debugging Tips

🔧 Common errors and how to fix:

ProblemSymptomFix
Port in useApp fails to startChange server.port
H2 DB errorCannot connectFix DB URL or check logs
NullPointerMissing @AutowiredAdd annotation
App not accessible in DockerNo port exposedUse -p 8080:8080 in Docker run

✅ Summary

TaskTool
Build appSpring Boot + Maven
Test locallyCurl/Postman
Deploy in containerDocker
AutomateGitHub Actions
Monitor healthActuator /actuator/health
DebugLogs, Postman, Spring DevTools

No comments:

Post a Comment