如何在不依赖Spring Security的情况下使用BCryptPasswordEncoder
解决方案
步骤1:调整项目依赖
移除完整的Spring Security Starter依赖,仅引入Spring Security Crypto模块(这是包含BCryptPasswordEncoder和PasswordEncoder的核心模块,不附带安全自动配置)。
以Gradle为例,修改依赖配置如下:
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' // 移除完整的Spring Security Starter // implementation 'org.springframework.boot:spring-boot-starter-security' // 添加单独的加密核心模块 implementation 'org.springframework.security:spring-security-crypto' implementation 'org.springframework.boot:spring-boot-starter-web-services' implementation 'org.springframework.boot:spring-boot-starter-actuator'
如果是Maven项目,对应依赖修改为:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-crypto</artifactId> </dependency>
步骤2:保留原有密码加密工具类
你之前编写的PasswordEncoderUtil无需修改,因为BCryptPasswordEncoder和PasswordEncoder接口都属于spring-security-crypto模块,代码可直接复用:
import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; @Component public class PasswordEncoderUtil { @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
步骤3:验证效果
- 项目不会加载Spring Security的自动配置逻辑,因此默认登录页面不会出现。
- 依然可以通过
@Autowired注入PasswordEncoder,在用户注册时调用encode()方法加密密码后存储到JPA中。
内容的提问来源于stack exchange,提问作者krish-alt
相关产品推荐
相关产品推荐

