blob: fae9926300b3230ee659cb37d69c5c07e5410331 [file] [log] [blame]
package com.g9.g9backend.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.AES;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment; // 正确导入 Spring 的 Environment
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@MapperScan({"com.g9.g9backend.mapper"})
public class MybatisPlusConfig {
private final Environment environment;
public MybatisPlusConfig(Environment environment) {
this.environment = environment;
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
// 生成 AES 密钥 (只需运行一次,生成后妥善保存)
public static void main(String[] args) {
String randomKey = AES.generateRandomKey();
System.out.println("生成的 AES 密钥: " + randomKey);
String encryptedPassword = AES.encrypt("", randomKey); // 对实际的数据库密码进行加密
System.out.println("加密后的密码: " + encryptedPassword);
}
// 注册自定义密码解码器
@Bean
public PasswordDecoder passwordDecoder() {
return new CustomPasswordDecoder(environment.getProperty("mybatis-plus.aes-key"));
}
// 自定义密码解码器接口
public interface PasswordDecoder {
String decode(String encodedPassword);
}
// 自定义密码解码器实现
public static class CustomPasswordDecoder implements PasswordDecoder {
private final String aesKey;
public CustomPasswordDecoder(String aesKey) {
this.aesKey = aesKey;
}
@Override
public String decode(String encodedPassword) {
try {
return AES.decrypt(encodedPassword, aesKey);
} catch (Exception e) {
throw new RuntimeException("密码解密失败", e);
}
}
}
}