Appearance
Spring Boot 1.x 版本指南
官方介绍
Spring Boot 1.x 是 Pivotal Software 推出的 Spring Boot 框架的早期版本系列,基于 Spring Framework 4.x 构建。1.x 版本是 Spring Boot 的奠基之作,首次提出了"约定优于配置"的理念,极大地简化了 Spring 应用的初始搭建以及开发过程。这个版本为后续版本的发展奠定了坚实的基础,标志着 Spring 生态系统向简化开发方向的重要转变。
Spring Boot 1.x 旨在简化 Spring 应用的初始搭建以及开发过程,通过自动配置、起步依赖和生产就绪特性,让开发者能够快速创建独立的、生产级别的基于 Spring 框架的应用程序。
版本特性
核心特性
- Java 6+ 最低要求: 支持 Java 6 及更高版本,向下兼容性好
- 自动配置: 根据类路径中的依赖自动配置 Spring 应用
- 起步依赖: 简化 Maven/Gradle 依赖管理
- 嵌入式服务器: 内置 Tomcat 7/8, Jetty 8/9, Undertow 1.1+
- 指标监控: 内置 Actuator 提供健康检查和监控端点
- 外部化配置: 支持多种外部配置方式
1.x 版本演进
- 1.0.x: 初始版本,奠定 Spring Boot 核心理念
- 1.1.x: 增强了对 Groovy 的支持,改进了自动配置
- 1.2.x: 增强了对 Spring Data 的集成,改进了性能
- 1.3.x: 增强了对 Docker 的支持,改进了启动时间
- 1.4.x: 增强了对 Kotlin 的支持,改进了开发体验
- 1.5.x: 最终维护版本,持续的安全和 bug 修复
官方获取地址
bash
# 通过 Maven 创建 Spring Boot 1.x 项目
mvn archetype:generate -DgroupId=com.example \
-DartifactId=spring-boot-1-app \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DinteractiveMode=false
# 或者使用 Spring Boot CLI
spring init --dependencies=web --boot-version=1.5.22.RELEASE spring-boot-1-project或者通过 Spring Initializr 网站:
- 访问 https://start.spring.io
- 选择 Spring Boot 1.5.x 版本
环境要求
- Java: JDK 6 或更高版本(JDK 7+ 推荐)
- Maven: 3.2+ 或 Gradle 2.9+
- 构建工具: Maven 或 Gradle
- 操作系统: 跨平台支持(Linux、Windows、macOS)
- 嵌入式服务器: Tomcat 7/8, Jetty 8/9, Undertow 1.1+
部署方法
1. 项目初始化
bash
# 使用 Spring Initializr 创建项目
curl https://start.spring.io/starter.tgz \
-d type=maven-project \
-d dependencies=web,actuator \
-d bootVersion=1.5.22.RELEASE \
-o spring-boot-1-app.tar.gz
tar -xzf spring-boot-1-app.tar.gz
cd spring-boot-1-app2. 构建项目
bash
# 使用 Maven
./mvnw clean compile
./mvnw clean package
./mvnw clean spring-boot:run
# 使用 Gradle
./gradlew clean compileJava
./gradlew clean build
./gradlew clean bootRun3. 配置文件说明
Spring Boot 1.x 使用以下配置文件:
application.properties
properties
# 服务器配置
server.port=8080
server.context-path=/app
# Spring Boot Actuator 配置
management.context-path=/manage
endpoints.enabled=true
endpoints.health.enabled=true
endpoints.info.enabled=true
# 日志配置
logging.level.root=INFO
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
# Redis 配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.database=0application.yml
yaml
server:
port: 8080
context-path: /app
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: user
password: password
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
hibernate:
naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
redis:
host: localhost
port: 6379
database: 0
management:
context-path: /manage
endpoints:
enabled: true
health:
enabled: true
info:
enabled: true4. 打包和部署
bash
# 构建可执行 JAR
./mvnw clean package
# 运行应用
java -jar target/spring-boot-1-app-0.0.1-SNAPSHOT.jar
# 或带参数运行
java -jar target/spring-boot-1-app-0.0.1-SNAPSHOT.jar --server.port=9090二次开发
自定义配置类
创建自定义配置类示例:
src/main/java/com/example/config/AppConfig.java
java
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public MyCustomService myCustomService() {
return new MyCustomService();
}
}
class MyCustomService {
public String getServiceInfo() {
return "Custom service running on Spring Boot 1.x";
}
}自定义控制器
src/main/java/com/example/controller/CustomController.java
java
package com.example.controller;
import com.example.config.MyCustomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class CustomController {
@Autowired
private MyCustomService myCustomService;
@GetMapping("/info")
public String getInfo() {
return "Spring Boot 1.x Application - " + myCustomService.getServiceInfo();
}
@GetMapping("/health")
public String getHealth() {
return "Application is healthy";
}
}自定义过滤器
src/main/java/com/example/filter/CustomFilter.java
java
package com.example.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CustomFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// 添加自定义头
httpResponse.setHeader("X-Powered-By", "Spring Boot 1.x");
long startTime = System.currentTimeMillis();
chain.doFilter(request, response);
long duration = System.currentTimeMillis() - startTime;
System.out.println("Request processed in " + duration + " ms");
}
}配置示例
数据库配置示例
application.properties
properties
# MySQL 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/springboot1?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Tomcat 连接池配置
spring.datasource.tomcat.max-active=20
spring.datasource.tomcat.min-idle=5
spring.datasource.tomcat.initial-size=5
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.validation-query=SELECT 1
# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect安全配置示例
src/main/java/com/example/config/SecurityConfig.java
java
package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build());
manager.createUser(User.withDefaultPasswordEncoder()
.username("admin")
.password("admin")
.roles("USER", "ADMIN")
.build());
return manager;
}
}缓存配置示例
src/main/java/com/example/config/CacheConfig.java
java
package com.example.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("users", "books", "orders");
}
}src/main/java/com/example/service/UserService.java
java
package com.example.service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Cacheable("users")
public String getUserById(Long id) {
// 模拟数据库查询
System.out.println("Fetching user from DB for ID: " + id);
return "User Details for ID: " + id;
}
}Demo 示例
REST API 示例
src/main/java/com/example/demo/DemoApplication.java
java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}src/main/java/com/example/demo/model/User.java
java
package com.example.demo.model;
import javax.persistence.*;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false, unique = true)
private String email;
public User() {}
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}src/main/java/com/example/demo/repository/UserRepository.java
java
package com.example.demo.repository;
import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
}src/main/java/com/example/demo/controller/UserController.java
java
package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userRepository.findAll();
return new ResponseEntity<>(users, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
Optional<User> user = userRepository.findById(id);
return user.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = userRepository.save(user);
return new ResponseEntity<>(savedUser, HttpStatus.CREATED);
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
Optional<User> user = userRepository.findById(id);
if (user.isPresent()) {
User updatedUser = user.get();
updatedUser.setName(userDetails.getName());
updatedUser.setEmail(userDetails.getEmail());
userRepository.save(updatedUser);
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<HttpStatus> deleteUser(@PathVariable Long id) {
Optional<User> user = userRepository.findById(id);
if (user.isPresent()) {
userRepository.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}常见问题和解决方案
1. 启动失败问题
检查日志以确定启动失败的原因:
bash
# 查看启动日志
java -jar app.jar --debug2. 端口冲突问题
properties
# 使用随机端口
server.port=0
# 或者配置多个应用实例
server.port=${PORT:8080}3. 数据库连接问题
确保数据库服务正在运行并正确配置连接参数:
properties
spring.datasource.url=jdbc:mysql://localhost:3306/dbname
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver4. Actuator 安全配置
在生产环境中限制 actuator 端点的访问:
properties
management.security.enabled=true
security.basic.enabled=true
endpoints.health.sensitive=true
endpoints.info.sensitive=true性能优化
连接池配置
properties
# Tomcat 连接池配置
spring.datasource.tomcat.max-active=20
spring.datasource.tomcat.min-idle=5
spring.datasource.tomcat.initial-size=5
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.validation-query=SELECT 1JVM 优化
bash
# 推荐的 JVM 参数
JAVA_OPTS="-Xms512m -Xmx1024m \
-XX:+UseG1GC -XX:MaxGCPauseMillis=200 \
-Djava.awt.headless=true \
-Dfile.encoding=UTF-8"Actuator 配置
properties
# 性能监控配置
endpoints.metrics.enabled=true
endpoints.shutdown.enabled=true
endpoints.health.sensitive=false
management.security.enabled=falseDocker 部署示例
Dockerfile
dockerfile
FROM openjdk:8-jre-alpine
LABEL maintainer="Your Name <your.email@example.com>"
WORKDIR /app
COPY target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
HEALTHCHECK --interval=30s --timeout=3s --start-period=60s --retries=3 \
CMD curl -f http://localhost:8080/manage/health || exit 1Docker Compose 配置
yaml
version: '3.8'
services:
spring-boot-app:
build: .
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=docker
- JAVA_OPTS=-Xms512m -Xmx1024m
depends_on:
- mysql
- redis
networks:
- spring-boot-net
mysql:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_DATABASE: springboot1
MYSQL_USER: user
MYSQL_PASSWORD: password
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
networks:
- spring-boot-net
redis:
image: redis:5-alpine
ports:
- "6379:6379"
volumes:
- redis_data:/data
networks:
- spring-boot-net
networks:
spring-boot-net:
driver: bridge
volumes:
mysql_data:
redis_data:Kubernetes 部署示例
Deployment 配置
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: spring-boot-app
labels:
app: spring-boot-app
spec:
replicas: 3
selector:
matchLabels:
app: spring-boot-app
template:
metadata:
labels:
app: spring-boot-app
spec:
containers:
- name: spring-boot
image: spring-boot-1-app:latest
ports:
- containerPort: 8080
env:
- name: SPRING_PROFILES_ACTIVE
value: "kubernetes"
- name: JAVA_OPTS
value: "-Xms512m -Xmx1024m -XX:+UseG1GC"
resources:
requests:
memory: "512Mi"
cpu: "250m"
limits:
memory: "1Gi"
cpu: "500m"
livenessProbe:
httpGet:
path: /manage/health
port: 8080
initialDelaySeconds: 120
periodSeconds: 30
readinessProbe:
httpGet:
path: /manage/health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
name: spring-boot-service
spec:
selector:
app: spring-boot-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: LoadBalancer监控和可观测性
Actuator 配置
properties
# Actuator 端点配置
endpoints.enabled=true
endpoints.health.enabled=true
endpoints.info.enabled=true
endpoints.metrics.enabled=true
endpoints.env.enabled=true
endpoints.configprops.enabled=true
endpoints.beans.enabled=true
# 安全配置
management.security.enabled=true
security.basic.enabled=true总结
Spring Boot 1.x 是 Spring Boot 发展历程中的重要里程碑,它首次提出了"开箱即用"的理念,极大地简化了 Spring 应用的开发。虽然 1.x 版本现在已经不再维护,但它的设计理念和核心功能为后续版本的发展奠定了坚实的基础。1.x 版本的重要贡献包括自动配置、起步依赖、嵌入式服务器等特性,这些特性至今仍是 Spring Boot 的核心组成部分。