SpringBoot Web开发(请求,响应,分层解耦)
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/api")
public class ApiController {
private final Service service;
public ApiController(Service service) {
this.service = service;
}
@GetMapping("/greeting")
@ResponseBody
public Greeting greeting() {
return service.greet();
}
}
// Service.java
public interface Service {
Greeting greet();
}
// ServiceImpl.java
import org.springframework.stereotype.Service;
@Service
public class ServiceImpl implements Service {
@Override
public Greeting greet() {
return new Greeting("Hello, Spring Boot!");
}
}
// Greeting.java
public class Greeting {
private final String content;
public Greeting(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
在这个简化的代码示例中,我们创建了一个名为ApiController
的Spring Boot控制器,它处理对/api/greeting
的GET请求。它使用依赖注入的Service
实例来处理请求,并返回一个简单的问候Greeting
对象作为JSON响应。这个例子展示了如何在Spring Boot应用中实现请求处理、服务层的定义以及响应的生成,体现了分层架构的概念。
评论已关闭