blob: fae9926300b3230ee659cb37d69c5c07e5410331 [file] [log] [blame]
xiukira687b9cb2025-05-29 15:15:02 +08001package com.g9.g9backend.config;
2
3import com.baomidou.mybatisplus.annotation.DbType;
Seamher3eb882d2025-06-09 23:56:09 +08004import com.baomidou.mybatisplus.core.toolkit.AES;
xiukira687b9cb2025-05-29 15:15:02 +08005import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
6import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
7import org.mybatis.spring.annotation.MapperScan;
8import org.springframework.context.annotation.Bean;
9import org.springframework.context.annotation.Configuration;
Seamher3eb882d2025-06-09 23:56:09 +080010import org.springframework.core.env.Environment; // 正确导入 Spring 的 Environment
xiukira687b9cb2025-05-29 15:15:02 +080011import org.springframework.transaction.annotation.EnableTransactionManagement;
12
13@Configuration
14@EnableTransactionManagement
Seamher3eb882d2025-06-09 23:56:09 +080015@MapperScan({"com.g9.g9backend.mapper"})
xiukira687b9cb2025-05-29 15:15:02 +080016public class MybatisPlusConfig {
17
Seamher3eb882d2025-06-09 23:56:09 +080018 private final Environment environment;
19
20 public MybatisPlusConfig(Environment environment) {
21 this.environment = environment;
22 }
23
xiukira687b9cb2025-05-29 15:15:02 +080024 @Bean
25 public MybatisPlusInterceptor mybatisPlusInterceptor() {
Seamher3eb882d2025-06-09 23:56:09 +080026 MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
27 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
28 return interceptor;
xiukira687b9cb2025-05-29 15:15:02 +080029 }
30
Seamher3eb882d2025-06-09 23:56:09 +080031 // 生成 AES 密钥 (只需运行一次,生成后妥善保存)
32 public static void main(String[] args) {
33 String randomKey = AES.generateRandomKey();
34 System.out.println("生成的 AES 密钥: " + randomKey);
35 String encryptedPassword = AES.encrypt("", randomKey); // 对实际的数据库密码进行加密
36 System.out.println("加密后的密码: " + encryptedPassword);
37 }
38
39 // 注册自定义密码解码器
40 @Bean
41 public PasswordDecoder passwordDecoder() {
42 return new CustomPasswordDecoder(environment.getProperty("mybatis-plus.aes-key"));
43 }
44
45 // 自定义密码解码器接口
46 public interface PasswordDecoder {
47 String decode(String encodedPassword);
48 }
49
50 // 自定义密码解码器实现
51 public static class CustomPasswordDecoder implements PasswordDecoder {
52
53 private final String aesKey;
54
55 public CustomPasswordDecoder(String aesKey) {
56 this.aesKey = aesKey;
57 }
58
59 @Override
60 public String decode(String encodedPassword) {
61 try {
62 return AES.decrypt(encodedPassword, aesKey);
63 } catch (Exception e) {
64 throw new RuntimeException("密码解密失败", e);
65 }
66 }
67 }
68}