You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何自定义注解实现通用WebSecurityConfig配置复用

实现方案

Java注解本身不支持继承普通类,你可以通过@Import注解关联自定义启动注解和公共配置类实现需求,操作步骤如下:

1. 抽取公共安全配置类

在公共库中把你所有项目通用的安全逻辑封装为独立的配置类,正常继承WebSecurityConfigurerAdapter即可:

@Configuration
@EnableWebSecurity
public class CommonWebSecurityConfig extends WebSecurityConfigurerAdapter {
    // 写入你所有项目共用的安全配置逻辑,示例如下
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .csrf().disable();
        // 其他通用规则
    }
}

2. 编写自定义启用注解

在公共库中定义@EnableGlobalSecurity注解,通过@Import导入上面的公共配置类:

import java.lang.annotation.*;
import org.springframework.context.annotation.Import;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(CommonWebSecurityConfig.class)
public @interface EnableGlobalSecurity {
    // 可按需添加自定义属性,用来给公共配置传入差异化参数
}

3. 业务项目使用

业务项目引入公共库之后,只需要在启动类或者任意配置类上添加@EnableGlobalSecurity注解,就会自动加载这套公共安全配置。


可选扩展能力

如果部分项目需要调整部分默认规则,可以在公共配置中做如下适配:

  • 给公共配置里的默认Bean添加@ConditionalOnMissingBean注解,业务项目自定义同类型Bean即可覆盖默认实现
  • 预留配置回调接口,业务项目实现接口即可自定义部分规则,不需要修改公共库代码

小提示:如果你使用Spring Security 5.7及以上版本,WebSecurityConfigurerAdapter已被官方废弃,你可以把公共配置改成注册SecurityFilterChain类型Bean的写法,导入逻辑完全一致


内容的提问来源于stack exchange,提问作者Daniel Pomrehn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 05:06:02