Java Boot启动案例怎么编写

wen java案例 29

本文目录导读:

Java Boot启动案例怎么编写

  1. 基础Maven项目结构
  2. pom.xml配置
  3. 主启动类
  4. 控制器示例
  5. 配置文件
  6. 高级配置(可选)
  7. 启动和访问
  8. 单元测试

我来为您介绍一个完整的Spring Boot启动案例,包含基础配置和常见组件。

基础Maven项目结构

项目目录结构

my-springboot-app/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           ├── Application.java
│   │   │           ├── controller/
│   │   │           │   └── HelloController.java
│   │   │           └── config/
│   │   │               └── WebConfig.java
│   │   └── resources/
│   │       ├── application.properties
│   │       └── static/
│   └── test/
│       └── java/
│           └── com/
│               └── example/
│                   └── ApplicationTests.java
└── pom.xml

pom.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- 继承Spring Boot父项目 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>my-springboot-app</artifactId>
    <version>1.0.0</version>
    <name>My Spring Boot Application</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!-- Spring Boot Web启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Boot测试依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <!-- Spring Boot Maven插件 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

主启动类

package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
 * Spring Boot应用主启动类
 */
@SpringBootApplication  // 组合注解,包含@Configuration、@EnableAutoConfiguration、@ComponentScan
public class Application extends SpringBootServletInitializer {
    public static void main(String[] args) {
        // 启动Spring Boot应用
        SpringApplication.run(Application.class, args);
    }
}

控制器示例

package com.example.controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import java.util.HashMap;
import java.util.Map;
@RestController  // 组合注解,相当于@Controller + @ResponseBody
@RequestMapping("/api")
public class HelloController {
    @Value("${app.name:Spring Boot App}")
    private String appName;
    /**
     * 基础GET请求
     */
    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
    /**
     * 返回JSON数据
     */
    @GetMapping("/info")
    public Map<String, Object> getInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("appName", appName);
        info.put("version", "1.0.0");
        info.put("status", "running");
        return info;
    }
    /**
     * 带路径参数的GET请求
     */
    @GetMapping("/user/{id}")
    public String getUser(@PathVariable Long id) {
        return "User ID: " + id;
    }
    /**
     * 带查询参数的GET请求
     */
    @GetMapping("/search")
    public String search(@RequestParam(name = "q", defaultValue = "") String query) {
        return "Searching for: " + query;
    }
    /**
     * POST请求,接收JSON数据
     */
    @PostMapping("/user")
    public Map<String, Object> createUser(@RequestBody Map<String, Object> user) {
        user.put("created", true);
        user.put("timestamp", System.currentTimeMillis());
        return user;
    }
}

配置文件

application.properties

# 服务器配置
server.port=8080
server.servlet.context-path=/myapp
# 应用名称
spring.application.name=my-springboot-app
app.name=My Custom App
# 开发环境配置
spring.profiles.active=dev
# 日志配置
logging.level.com.example=DEBUG
logging.file.name=logs/app.log
# 字符编码
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true

application-dev.properties(开发环境)

# 开发环境特定配置
server.port=8080
logging.level.com.example=TRACE
spring.devtools.restart.enabled=true

application-prod.properties(生产环境)

# 生产环境特定配置
server.port=80
logging.level.com.example=WARN
spring.devtools.restart.enabled=false

高级配置(可选)

WebConfig.java - Web配置

package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 配置跨域请求
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加拦截器
        registry.addInterceptor(new LogInterceptor())
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/hello");
    }
}

自定义拦截器

package com.example.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, 
                            HttpServletResponse response, 
                            Object handler) throws Exception {
        System.out.println("Request URL: " + request.getRequestURL());
        System.out.println("Start Time: " + System.currentTimeMillis());
        return true;  // 继续执行
    }
    @Override
    public void afterCompletion(HttpServletRequest request, 
                               HttpServletResponse response, 
                               Object handler, 
                               Exception ex) throws Exception {
        System.out.println("End Time: " + System.currentTimeMillis());
    }
}

启动和访问

IDE启动

  1. 在IDE中打开项目
  2. 找到Application.java主类
  3. 右键点击 -> Run 'Application'

Maven命令行启动

# Linux/Mac
./mvnw spring-boot:run
# Windows
mvnw.cmd spring-boot:run

编译后运行JAR包

# 打包
mvn clean package
# 运行
java -jar target/my-springboot-app-1.0.0.jar
# 指定端口
java -jar target/my-springboot-app-1.0.0.jar --server.port=8888
# 指定环境
java -jar target/my-springboot-app-1.0.0.jar --spring.profiles.active=prod

测试访问

# 基础请求
curl http://localhost:8080/myapp/api/hello
# 路径参数
curl http://localhost:8080/myapp/api/user/123
# 查询参数
curl http://localhost:8080/myapp/api/search?q=spring
# POST请求
curl -X POST http://localhost:8080/myapp/api/user \
  -H "Content-Type: application/json" \
  -d '{"name":"John","age":30}'

单元测试

package com.example;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApplicationTests {
    @LocalServerPort
    private int port;
    @Autowired
    private TestRestTemplate restTemplate;
    @Test
    void testHelloEndpoint() {
        ResponseEntity<String> response = restTemplate
            .getForEntity("http://localhost:" + port + "/myapp/api/hello", String.class);
        assertThat(response.getBody()).isEqualTo("Hello, Spring Boot!");
    }
}

这个完整的Spring Boot启动案例包含了:

  • 基础项目结构
  • pom.xml依赖配置
  • 主启动类
  • REST控制器
  • 配置文件(多环境)
  • 跨域配置
  • 拦截器
  • 单元测试

您可以根据实际需求添加更多功能,如数据库访问、安全认证等。

抱歉,评论功能暂时关闭!