feat: 添加用户数据初始化功能并优化配置管理
refactor: 重构CORS配置使其从配置文件读取 refactor: 移除无用分类和消息初始化代码 build: 更新pom.xml依赖项 docs: 拆分应用配置文件为环境特定配置
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
package com.qf.myafterprojecy.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
@@ -12,31 +13,50 @@ import org.springframework.web.filter.CorsFilter;
|
||||
@Configuration
|
||||
public class CorsConfig {
|
||||
|
||||
// 从配置文件中读取CORS配置
|
||||
@Value("${cors.allowed-origins}")
|
||||
private String allowedOrigins;
|
||||
|
||||
@Value("${cors.allowed-methods}")
|
||||
private String allowedMethods;
|
||||
|
||||
@Value("${cors.allowed-headers}")
|
||||
private String allowedHeaders;
|
||||
|
||||
@Value("${cors.allow-credentials}")
|
||||
private Boolean allowCredentials;
|
||||
|
||||
@Value("${cors.max-age:3600}")
|
||||
private Long maxAge;
|
||||
|
||||
|
||||
/**
|
||||
* 创建CORS过滤器,配置跨域请求的规则
|
||||
* 从配置文件中读取CORS配置,实现配置的统一管理
|
||||
*/
|
||||
@Bean
|
||||
public CorsFilter corsFilter() {
|
||||
// 创建CORS配置对象
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
|
||||
// 允许的来源,使用通配符模式
|
||||
config.addAllowedOriginPattern("*");
|
||||
|
||||
|
||||
// 允许的来源,从配置文件读取并分割
|
||||
String[] originsArray = allowedOrigins.split(",");
|
||||
for (String origin : originsArray) {
|
||||
config.addAllowedOrigin(origin.trim());
|
||||
}
|
||||
|
||||
// 允许携带凭证(如Cookie)
|
||||
config.setAllowCredentials(true);
|
||||
|
||||
// 明确列出允许的HTTP方法,比使用通配符更安全
|
||||
config.addAllowedMethod("GET");
|
||||
config.addAllowedMethod("POST");
|
||||
config.addAllowedMethod("PUT");
|
||||
config.addAllowedMethod("DELETE");
|
||||
config.addAllowedMethod("OPTIONS");
|
||||
config.addAllowedMethod("PATCH");
|
||||
|
||||
// 允许的请求头
|
||||
config.addAllowedHeader("*");
|
||||
|
||||
config.setAllowCredentials(allowCredentials);
|
||||
|
||||
// 允许的HTTP方法,从配置文件读取并分割
|
||||
String[] methodsArray = allowedMethods.split(",");
|
||||
for (String method : methodsArray) {
|
||||
config.addAllowedMethod(method.trim());
|
||||
}
|
||||
|
||||
// 允许的请求头,从配置文件读取
|
||||
config.addAllowedHeader(allowedHeaders);
|
||||
|
||||
// 明确暴露的响应头,对于JWT认证很重要
|
||||
config.addExposedHeader("Authorization");
|
||||
config.addExposedHeader("Content-Type");
|
||||
@@ -44,16 +64,16 @@ public class CorsConfig {
|
||||
config.addExposedHeader("Accept");
|
||||
config.addExposedHeader("Access-Control-Allow-Origin");
|
||||
config.addExposedHeader("Access-Control-Allow-Credentials");
|
||||
|
||||
// 设置预检请求的有效期(秒)
|
||||
config.setMaxAge(86400L); // 增加到24小时,减少预检请求次数
|
||||
|
||||
|
||||
// 设置预检请求的有效期(秒),从配置文件读取
|
||||
config.setMaxAge(maxAge);
|
||||
|
||||
// 创建基于URL的CORS配置源
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
|
||||
|
||||
// 为所有路径应用CORS配置
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
|
||||
|
||||
// 返回配置好的CORS过滤器
|
||||
return new CorsFilter(source);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ public class PasswordEncoderConfig {
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
// 强度设置为10,这是一个平衡安全性和性能的值
|
||||
// 数值越高,计算成本越大,安全性越好
|
||||
return new BCryptPasswordEncoder(10);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ public class SecurityConfig {
|
||||
response.setHeader("Access-Control-Allow-Credentials", "true");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
|
||||
response.setHeader("Access-Control-Allow-Headers", "*");
|
||||
response.setHeader("Access-Control-Max-Age", "86400");
|
||||
response.setHeader("Access-Control-Max-Age", "3600");
|
||||
|
||||
// 如果是预检请求,直接返回200
|
||||
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
|
||||
|
||||
@@ -21,6 +21,7 @@ import java.util.List;
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/articles")
|
||||
|
||||
@Validated
|
||||
public class ArticleController {
|
||||
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
// package com.qf.myafterprojecy.init;
|
||||
|
||||
// import com.qf.myafterprojecy.pojo.Category;
|
||||
// import com.qf.myafterprojecy.repository.CategoryRepository;
|
||||
// import org.slf4j.Logger;
|
||||
// import org.slf4j.LoggerFactory;
|
||||
// import org.springframework.beans.factory.annotation.Autowired;
|
||||
// import org.springframework.boot.ApplicationArguments;
|
||||
// import org.springframework.boot.ApplicationRunner;
|
||||
// import org.springframework.stereotype.Component;
|
||||
|
||||
// import java.time.LocalDateTime;
|
||||
// import java.util.ArrayList;
|
||||
// import java.util.List;
|
||||
|
||||
// /**
|
||||
// * 分类数据初始化类,用于在应用启动时初始化分类数据
|
||||
// */
|
||||
// @Component
|
||||
// public class CategoryDataInit implements ApplicationRunner {
|
||||
|
||||
// private static final Logger logger = LoggerFactory.getLogger(CategoryDataInit.class);
|
||||
|
||||
// @Autowired
|
||||
// private CategoryRepository categoryRepository;
|
||||
|
||||
// @Override
|
||||
// public void run(ApplicationArguments args) throws Exception {
|
||||
// logger.info("===== 分类数据初始化开始 =====");
|
||||
|
||||
// // 检查数据库中是否已有分类数据
|
||||
// long count = categoryRepository.count();
|
||||
// logger.info("当前数据库中分类数量: {}", count);
|
||||
|
||||
// // 如果没有分类数据,添加一些测试数据
|
||||
// if (count == 0) {
|
||||
// logger.info("数据库中没有分类数据,开始添加初始化数据...");
|
||||
// addInitialCategories();
|
||||
// } else {
|
||||
// logger.info("数据库中已存在分类数据,无需初始化");
|
||||
// }
|
||||
|
||||
// logger.info("===== 分类数据初始化结束 =====");
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 添加初始分类数据
|
||||
// */
|
||||
// private void addInitialCategories() {
|
||||
// List<Category> categories = new ArrayList<>();
|
||||
|
||||
// // 创建几个常见的文章分类
|
||||
// Category category1 = new Category();
|
||||
// category1.setTypename("技术分享");
|
||||
// category1.setDescription("技术文章、教程、经验分享等");
|
||||
// category1.setCreatedAt(LocalDateTime.now());
|
||||
// category1.setUpdatedAt(LocalDateTime.now());
|
||||
// categories.add(category1);
|
||||
|
||||
// Category category2 = new Category();
|
||||
// category2.setTypename("生活随笔");
|
||||
// category2.setDescription("日常生活、心情记录、随笔等");
|
||||
// category2.setCreatedAt(LocalDateTime.now());
|
||||
// category2.setUpdatedAt(LocalDateTime.now());
|
||||
// categories.add(category2);
|
||||
|
||||
// Category category3 = new Category();
|
||||
// category3.setTypename("学习笔记");
|
||||
// category3.setDescription("学习过程中的笔记、总结等");
|
||||
// category3.setCreatedAt(LocalDateTime.now());
|
||||
// category3.setUpdatedAt(LocalDateTime.now());
|
||||
// categories.add(category3);
|
||||
|
||||
// Category category4 = new Category();
|
||||
// category4.setTypename("行业动态");
|
||||
// category4.setDescription("行业新闻、趋势分析等");
|
||||
// category4.setCreatedAt(LocalDateTime.now());
|
||||
// category4.setUpdatedAt(LocalDateTime.now());
|
||||
// categories.add(category4);
|
||||
|
||||
// // 保存分类数据到数据库
|
||||
// categoryRepository.saveAll(categories);
|
||||
// logger.info("成功添加 {} 条分类数据", categories.size());
|
||||
// }
|
||||
// }
|
||||
@@ -1,96 +0,0 @@
|
||||
// package com.qf.myafterprojecy.init;
|
||||
|
||||
// import com.qf.myafterprojecy.pojo.Message;
|
||||
// import com.qf.myafterprojecy.repository.MessageRepository;
|
||||
// import org.slf4j.Logger;
|
||||
// import org.slf4j.LoggerFactory;
|
||||
// import org.springframework.beans.factory.annotation.Autowired;
|
||||
// import org.springframework.boot.ApplicationArguments;
|
||||
// import org.springframework.boot.ApplicationRunner;
|
||||
// import org.springframework.stereotype.Component;
|
||||
|
||||
// import java.util.Date;
|
||||
|
||||
// /**
|
||||
// * 消息数据初始化类,用于在应用启动时为Message表添加默认的测试数据
|
||||
// */
|
||||
// @Component
|
||||
// public class MessageDataInit implements ApplicationRunner {
|
||||
|
||||
// private static final Logger logger = LoggerFactory.getLogger(MessageDataInit.class);
|
||||
|
||||
// @Autowired
|
||||
// private MessageRepository messageRepository;
|
||||
|
||||
// @Override
|
||||
// public void run(ApplicationArguments args) throws Exception {
|
||||
// logger.info("===== 消息数据初始化开始 =====");
|
||||
|
||||
// // 检查数据库中是否已有消息数据
|
||||
// long count = messageRepository.count();
|
||||
// logger.info("当前数据库中消息数量: {}", count);
|
||||
|
||||
// // 如果没有消息数据,添加一些测试数据
|
||||
// if (count == 0) {
|
||||
// logger.info("数据库中没有消息数据,开始添加初始化数据...");
|
||||
// addInitialMessages();
|
||||
// } else {
|
||||
// logger.info("数据库中已存在消息数据,无需初始化");
|
||||
// }
|
||||
|
||||
// logger.info("===== 消息数据初始化结束 =====");
|
||||
// }
|
||||
|
||||
// private void addInitialMessages() {
|
||||
// // 添加第一篇文章的评论
|
||||
// Message message1 = new Message();
|
||||
// message1.setNickname("系统用户");
|
||||
// message1.setEmail("system@example.com");
|
||||
// message1.setContent("这是系统自动添加的第一条评论,欢迎使用本系统!");
|
||||
// message1.setCreatedAt(new Date());
|
||||
// message1.setArticleid(1);
|
||||
// message1.setParentid(null); // 根评论
|
||||
// messageRepository.save(message1);
|
||||
|
||||
// // 添加回复
|
||||
// Message reply1 = new Message();
|
||||
// reply1.setNickname("管理员");
|
||||
// reply1.setEmail("admin@example.com");
|
||||
// reply1.setContent("感谢您的支持,如有任何问题请随时联系我们!");
|
||||
// reply1.setCreatedAt(new Date());
|
||||
// reply1.setArticleid(1);
|
||||
// reply1.setParentid(message1.getMessageid()); // 回复第一条评论
|
||||
// messageRepository.save(reply1);
|
||||
|
||||
// // 添加第二篇文章的评论
|
||||
// Message message2 = new Message();
|
||||
// message2.setNickname("访客");
|
||||
// message2.setEmail("visitor@example.com");
|
||||
// message2.setContent("这篇文章写得非常好,学到了很多知识。");
|
||||
// message2.setCreatedAt(new Date());
|
||||
// message2.setArticleid(2);
|
||||
// message2.setParentid(null);
|
||||
// messageRepository.save(message2);
|
||||
|
||||
// // 再添加一些测试数据
|
||||
// Message message3 = new Message();
|
||||
// message3.setNickname("测试用户1");
|
||||
// message3.setEmail("test1@example.com");
|
||||
// message3.setContent("这是测试内容1");
|
||||
// message3.setCreatedAt(new Date());
|
||||
// message3.setArticleid(1);
|
||||
// message3.setParentid(null);
|
||||
// messageRepository.save(message3);
|
||||
|
||||
// Message reply2 = new Message();
|
||||
// reply2.setNickname("测试用户2");
|
||||
// reply2.setEmail("test2@example.com");
|
||||
// reply2.setContent("回复测试内容1");
|
||||
// reply2.setCreatedAt(new Date());
|
||||
// reply2.setArticleid(1);
|
||||
// reply2.setParentid(message3.getMessageid());
|
||||
// messageRepository.save(reply2);
|
||||
|
||||
// logger.info("成功添加了{}条初始化消息数据", messageRepository.count());
|
||||
// }
|
||||
// }
|
||||
65
src/main/java/com/qf/myafterprojecy/init/UserDataInit.java
Normal file
65
src/main/java/com/qf/myafterprojecy/init/UserDataInit.java
Normal file
@@ -0,0 +1,65 @@
|
||||
package com.qf.myafterprojecy.init;
|
||||
|
||||
import com.qf.myafterprojecy.pojo.Users;
|
||||
import com.qf.myafterprojecy.repository.UsersRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 用户数据初始化类
|
||||
* 在应用启动时检查并创建管理员账号
|
||||
*/
|
||||
@Component
|
||||
public class UserDataInit implements ApplicationRunner {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(UserDataInit.class);
|
||||
|
||||
@Autowired
|
||||
private UsersRepository usersRepository;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
// 管理员账号信息
|
||||
private static final String ADMIN_USERNAME = "qf1121";
|
||||
private static final String ADMIN_PASSWORD = "qf1121";
|
||||
private static final String ADMIN_EMAIL = "admin@qf1121.com";
|
||||
private static final String ADMIN_PHONE = "13800138000";
|
||||
private static final Integer ADMIN_ROLE = 1; // 1表示管理员角色
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
logger.info("开始检查管理员账号...");
|
||||
|
||||
// 检查管理员账号是否已存在
|
||||
Optional<Users> adminUser = usersRepository.findByUsername(ADMIN_USERNAME);
|
||||
|
||||
if (adminUser.isPresent()) {
|
||||
logger.info("管理员账号 {} 已存在,无需创建", ADMIN_USERNAME);
|
||||
} else {
|
||||
// 创建管理员账号
|
||||
Users newAdmin = new Users();
|
||||
newAdmin.setUsername(ADMIN_USERNAME);
|
||||
// 加密密码
|
||||
newAdmin.setPassword(passwordEncoder.encode(ADMIN_PASSWORD));
|
||||
newAdmin.setEmail(ADMIN_EMAIL);
|
||||
newAdmin.setPhone(ADMIN_PHONE);
|
||||
newAdmin.setRole(ADMIN_ROLE);
|
||||
newAdmin.setCreateTime(LocalDateTime.now());
|
||||
try {
|
||||
usersRepository.save(newAdmin);
|
||||
logger.info("管理员账号 {} 创建成功", ADMIN_USERNAME);
|
||||
} catch (Exception e) {
|
||||
logger.error("创建管理员账号失败: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ public class NonsenseDto {
|
||||
private Integer status;//状态 0:未发表 1:已发表 2:已删除
|
||||
|
||||
private Date time;
|
||||
|
||||
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
package com.qf.myafterprojecy.pojo.dto;
|
||||
|
||||
import javax.ws.rs.DefaultValue;
|
||||
|
||||
public class PageDto {
|
||||
|
||||
private Integer status;
|
||||
@DefaultValue("0")
|
||||
private Integer page;
|
||||
@DefaultValue("10")
|
||||
private Integer size;
|
||||
// 数据验证
|
||||
public void validate() {
|
||||
|
||||
63
src/main/resources/application-dev.properties
Normal file
63
src/main/resources/application-dev.properties
Normal file
@@ -0,0 +1,63 @@
|
||||
# ====================================================================
|
||||
# 开发环境配置文件
|
||||
# 说明:此配置用于本地开发和调试,只包含开发环境特定配置
|
||||
# 通用配置请参考主配置文件 application.properties
|
||||
# ====================================================================
|
||||
|
||||
# 应用基本配置 - 开发特定
|
||||
server.port=7070
|
||||
|
||||
# ====================================================================
|
||||
# 数据库与JPA配置 - 开发用
|
||||
# ====================================================================
|
||||
spring.datasource.url=jdbc:mysql://localhost:3306/webproject?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&createDatabaseIfNotExist=true&allowPublicKeyRetrieval=true
|
||||
spring.datasource.username=root
|
||||
spring.datasource.password=123456
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
|
||||
# 数据库连接池配置(开发环境简化版)
|
||||
spring.datasource.hikari.maximum-pool-size=5
|
||||
spring.datasource.hikari.minimum-idle=2
|
||||
|
||||
# JPA配置(开发环境使用update以便自动创建/更新表结构)
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.jpa.show-sql=true
|
||||
spring.jpa.properties.hibernate.format_sql=true
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
|
||||
|
||||
# ====================================================================
|
||||
# JWT 配置 - 开发用(方便调试,密钥较短,过期时间短)
|
||||
# ====================================================================
|
||||
jwt.secret=devSecretKey2024ForLocalDevelopment
|
||||
jwt.expiration=3600000 # 1小时过期,方便调试
|
||||
jwt.header=Authorization
|
||||
jwt.token-prefix=Bearer
|
||||
|
||||
# ====================================================================
|
||||
# 安全与CORS配置 - 开发用
|
||||
# ====================================================================
|
||||
# CORS配置(开发环境允许所有本地前端访问)
|
||||
cors.allowed-origins=http://localhost:3000,http://localhost:8080
|
||||
cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
|
||||
cors.allowed-headers=*
|
||||
cors.allow-credentials=true
|
||||
|
||||
# ====================================================================
|
||||
# 日志配置 - 开发用(详细日志便于调试)
|
||||
# ====================================================================
|
||||
logging.level.root=INFO
|
||||
logging.level.com.qf.myafterprojecy=DEBUG
|
||||
logging.level.org.springframework=INFO
|
||||
logging.level.org.hibernate.SQL=DEBUG
|
||||
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
|
||||
|
||||
# ====================================================================
|
||||
# 开发环境特有配置
|
||||
# ====================================================================
|
||||
# 热部署配置
|
||||
spring.devtools.restart.enabled=true
|
||||
spring.devtools.restart.additional-paths=src/main/java
|
||||
|
||||
# Actuator配置(开发环境开放更多端点便于调试)
|
||||
management.endpoints.web.exposure.include=*
|
||||
management.endpoint.health.show-details=always
|
||||
70
src/main/resources/application-prod.properties
Normal file
70
src/main/resources/application-prod.properties
Normal file
@@ -0,0 +1,70 @@
|
||||
# ====================================================================
|
||||
# 生产环境配置文件
|
||||
# 说明:此配置用于生产环境部署,敏感信息从环境变量读取
|
||||
# ====================================================================
|
||||
|
||||
# 应用基本配置 - 生产特定
|
||||
server.port=8080
|
||||
|
||||
# ====================================================================
|
||||
# 数据库与JPA配置 - 生产用
|
||||
# ====================================================================
|
||||
spring.datasource.url=${DB_URL:jdbc:mysql://mysql:3306/webproject?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai}
|
||||
spring.datasource.username=${DB_USERNAME:root}
|
||||
spring.datasource.password=${DB_PASSWORD:root}
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
|
||||
# 数据库连接池配置(生产环境优化版)
|
||||
spring.datasource.hikari.maximum-pool-size=20
|
||||
spring.datasource.hikari.minimum-idle=5
|
||||
spring.datasource.hikari.idle-timeout=300000
|
||||
spring.datasource.hikari.connection-timeout=20000
|
||||
spring.datasource.hikari.max-lifetime=1200000
|
||||
spring.datasource.hikari.connection-test-query=SELECT 1
|
||||
spring.datasource.hikari.pool-name=WebProjectHikariCP
|
||||
|
||||
# JPA配置(生产环境禁用自动DDL,避免意外修改表结构)
|
||||
spring.jpa.hibernate.ddl-auto=none
|
||||
spring.jpa.show-sql=false
|
||||
spring.jpa.properties.hibernate.format_sql=false
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
|
||||
spring.jpa.open-in-view=false
|
||||
|
||||
# JPA性能优化配置
|
||||
spring.jpa.properties.hibernate.jdbc.batch_size=30
|
||||
spring.jpa.properties.hibernate.order_inserts=true
|
||||
spring.jpa.properties.hibernate.order_updates=true
|
||||
|
||||
# ====================================================================
|
||||
# JWT 配置 - 生产用(敏感信息从环境变量读取)
|
||||
# ====================================================================
|
||||
jwt.secret=${JWT_SECRET:}
|
||||
jwt.expiration=${JWT_EXPIRATION:86400000}
|
||||
jwt.header=Authorization
|
||||
jwt.token-prefix=Bearer
|
||||
|
||||
# ====================================================================
|
||||
# 安全与CORS配置 - 生产用
|
||||
# ====================================================================
|
||||
# CORS配置(生产环境限制为具体域名)
|
||||
cors.allowed-origins=http://qf1121.top,https://qf1121.top,http://www.qf1121.top,https://www.qf1121.top
|
||||
cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
|
||||
cors.allowed-headers=*
|
||||
cors.allow-credentials=true
|
||||
cors.max-age=3600
|
||||
|
||||
# ====================================================================
|
||||
# 日志配置 - 生产用(精简日志,提高性能)
|
||||
# ====================================================================
|
||||
logging.level.root=WARN
|
||||
logging.level.com.qf.myafterprojecy=INFO
|
||||
logging.level.org.springframework.security=WARN
|
||||
logging.level.org.hibernate.SQL=ERROR
|
||||
logging.file.name=logs/web_project.log
|
||||
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
|
||||
# ====================================================================
|
||||
# API与应用配置 - 生产用
|
||||
# ====================================================================
|
||||
# Actuator配置(生产环境限制访问)
|
||||
management.endpoints.web.exposure.include=health,info
|
||||
management.endpoint.health.show-details=when_authorized
|
||||
@@ -1,95 +1,16 @@
|
||||
# 应用服务 WEB 访问端口
|
||||
server.port=8080
|
||||
# ====================================================================
|
||||
# 应用基本配置 - 通用配置
|
||||
# ====================================================================
|
||||
# 环境激活配置
|
||||
# 说明:默认激活开发环境,生产环境部署时应通过命令行参数或环境变量覆盖
|
||||
spring.profiles.active=dev
|
||||
|
||||
# 应用名称(通用配置)
|
||||
spring.application.name=web_project
|
||||
|
||||
# 数据库配置
|
||||
spring.datasource.url=jdbc:mysql://localhost:3306/webproject?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&createDatabaseIfNotExist=true&allowPublicKeyRetrieval=true
|
||||
spring.datasource.username=root
|
||||
spring.datasource.password=123456
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
|
||||
# 数据库连接池优化配置
|
||||
spring.datasource.hikari.maximum-pool-size=10
|
||||
spring.datasource.hikari.minimum-idle=5
|
||||
spring.datasource.hikari.idle-timeout=300000
|
||||
spring.datasource.hikari.connection-timeout=20000
|
||||
spring.datasource.hikari.max-lifetime=1200000
|
||||
spring.datasource.hikari.connection-test-query=SELECT 1
|
||||
spring.datasource.hikari.pool-name=WebProjectHikariCP
|
||||
|
||||
# JPA配置 - 生产环境建议将ddl-auto改为none
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.jpa.show-sql=false
|
||||
spring.jpa.properties.hibernate.format_sql=true
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
|
||||
spring.jpa.open-in-view=false
|
||||
|
||||
# JPA性能优化配置
|
||||
spring.jpa.properties.hibernate.jdbc.batch_size=30
|
||||
spring.jpa.properties.hibernate.order_inserts=true
|
||||
spring.jpa.properties.hibernate.order_updates=true
|
||||
# 暂时禁用Hibernate二级缓存和查询缓存
|
||||
# spring.jpa.properties.hibernate.cache.use_second_level_cache=true
|
||||
# spring.jpa.properties.hibernate.cache.use_query_cache=true
|
||||
|
||||
# 缓存配置
|
||||
spring.cache.type=redis
|
||||
spring.cache.redis.time-to-live=1800000
|
||||
spring.cache.redis.key-prefix=CACHE_
|
||||
spring.cache.redis.use-key-prefix=true
|
||||
spring.cache.redis.cache-null-values=false
|
||||
|
||||
# Redis配置
|
||||
spring.redis.host=localhost
|
||||
spring.redis.port=6379
|
||||
spring.redis.password=123456
|
||||
spring.redis.database=0
|
||||
spring.redis.timeout=10000ms
|
||||
# Redis连接池优化配置
|
||||
spring.redis.lettuce.pool.max-active=8
|
||||
spring.redis.lettuce.pool.max-wait=10000ms
|
||||
spring.redis.lettuce.pool.max-idle=8
|
||||
spring.redis.lettuce.pool.min-idle=2
|
||||
spring.redis.lettuce.shutdown-timeout=100ms
|
||||
|
||||
# 日志配置
|
||||
logging.level.root=INFO
|
||||
logging.level.com.qf.myafterprojecy=DEBUG
|
||||
logging.level.org.springframework.security=INFO
|
||||
logging.level.org.hibernate.SQL=WARN
|
||||
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
|
||||
# 日志文件配置
|
||||
logging.file.name=logs/web_project.log
|
||||
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
|
||||
# 确保控制台输出使用UTF-8编码
|
||||
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
|
||||
# 日志编码配置 - 强制使用UTF-8
|
||||
logging.charset.file=UTF-8
|
||||
logging.charset.console=UTF-8
|
||||
# Actuator配置 - 生产环境建议限制暴露的端点
|
||||
management.endpoints.web.exposure.include=health,info,metrics,prometheus
|
||||
management.endpoint.health.show-details=when_authorized
|
||||
management.metrics.export.prometheus.enabled=true
|
||||
|
||||
# JWT配置 - 生产环境应使用更安全的密钥和环境变量
|
||||
jwt.secret=myAfterProjectSecretKey2024SecureJwtTokenGeneration
|
||||
jwt.expiration=86400000
|
||||
jwt.header=Authorization
|
||||
jwt.token-prefix=Bearer
|
||||
|
||||
# CORS配置 - 生产环境应限制允许的源
|
||||
cors.allowed-origins=http://localhost:3000
|
||||
cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
|
||||
cors.allowed-headers=*,
|
||||
cors.allow-credentials=true
|
||||
cors.max-age=3600
|
||||
|
||||
# 安全配置增强
|
||||
security.basic.enabled=false
|
||||
security.ignored=/css/**,/js/**,/images/**,/favicon.ico
|
||||
|
||||
# 生产环境建议配置
|
||||
|
||||
# ====================================================================
|
||||
# 会话与编码配置 - 通用配置
|
||||
# ====================================================================
|
||||
# 会话配置
|
||||
server.servlet.session.timeout=30m
|
||||
server.session.tracking-modes=cookie
|
||||
@@ -97,33 +18,26 @@ server.session.tracking-modes=cookie
|
||||
# 国际化配置
|
||||
spring.web.locale=zh_CN
|
||||
spring.messages.encoding=UTF-8
|
||||
# 响应编码配置 - 确保所有响应使用UTF-8编码
|
||||
|
||||
# 响应编码配置(通用,所有环境保持一致)
|
||||
server.servlet.encoding.charset=UTF-8
|
||||
server.servlet.encoding.force=true
|
||||
server.servlet.encoding.force-request=true
|
||||
server.servlet.encoding.force-response=true
|
||||
server.servlet.encoding.enabled=true
|
||||
|
||||
# 配置控制台输出编码 - 通过日志系统配置确保中文显示正常
|
||||
# logging.pattern.console=%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{%5p} %clr{${PID}}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40logger{39}}{cyan} %clr{:}{faint} %m%n%wEx
|
||||
# ====================================================================
|
||||
# API与应用配置 - 通用配置
|
||||
# ====================================================================
|
||||
# API 文档配置(通用)
|
||||
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
|
||||
|
||||
# 配置Maven启动JVM参数(需在启动时通过命令行指定或在pom.xml中配置)
|
||||
# 实际使用时请在启动命令中添加:-Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8
|
||||
|
||||
# 更详细的日志配置 - 确保所有日志输出正确编码
|
||||
# logging.level.root=INFO
|
||||
# logging.level.org.springframework.web=DEBUG
|
||||
# logging.level.org.springframework.security=INFO
|
||||
# logging.level.com.qf.myafterprojecy=DEBUG
|
||||
|
||||
# 确保数据库连接编码正确
|
||||
spring.datasource.hikari.data-source-properties.useUnicode=true
|
||||
spring.datasource.hikari.data-source-properties.serverTimezone=Asia/Shanghai
|
||||
spring.datasource.hikari.data-source-properties.characterEncoding=utf-8
|
||||
|
||||
# 应用性能优化配置
|
||||
# 应用性能优化配置(通用)
|
||||
spring.main.allow-bean-definition-overriding=true
|
||||
spring.main.lazy-initialization=false
|
||||
|
||||
# API 文档配置
|
||||
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
|
||||
# ====================================================================
|
||||
# 说明:环境特定的配置(如数据库、JWT、CORS等)已移至对应的环境配置文件中
|
||||
# - 开发环境:application-dev.properties
|
||||
# - 生产环境:application-prod.properties
|
||||
# ====================================================================
|
||||
|
||||
Reference in New Issue
Block a user