src/
└── main/
└── java/
└── com/
└── example/
├── MyApp.java # Main class with @SpringBootApplication
├── GreetingService.java # @Component class (business logic)
└── GreetingController.java # @Component with @Autowired field
✅ 1. MyApp.java — Main Class
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
✅ 2. GreetingService.java — Component (Bean)
package com.example;
import org.springframework.stereotype.Component;
@Component
public class GreetingService {
public String getMessage() {
return "Hello testuser";
}
}
✅ 3. GreetingController.java — REST API Controller
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
@Autowired
private GreetingService greetingService; // Injected automatically
@GetMapping("/greet")
public String greet() {
return greetingService.getMessage(); // Returns "Hello testuser"
}
}
▶️ How to Run It
1. Build the project
mvn clean install
2. Run the Spring Boot app
mvn spring-boot:run
3. Test the endpoint
Open in browser or use curl:
Expected Output:
Hello testuser
No comments:
Post a Comment