要创建一个简单的REST服务,不使用Spring Boot,可以按照以下步骤:
创建一个Maven项目,或者使用其他构建工具如Gradle。
在项目的pom.xml文件中添加Spring框架的依赖项。以下是常用的依赖项:
org.springframework
spring-core
5.3.12.RELEASE
org.springframework
spring-web
5.3.12.RELEASE
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello/{name}")
public ResponseEntity sayHello(@PathVariable String name) {
String message = "Hello, " + name + "!";
return new ResponseEntity<>(message, HttpStatus.OK);
}
}
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example")
@Import({HelloController.class})
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
context.registerShutdownHook();
}
}
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
http://localhost:8080/api/hello/{name}
,其中{name}
是您要问候的人的名称。请注意,这只是一个简单的示例,仅包含必要的最小配置。如果需要更复杂的功能,您可能需要添加其他配置和依赖项。