惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Heimdal Security Blog
SecWiki News
SecWiki News
H
Hacker News: Front Page
N
News | PayPal Newsroom
L
LINUX DO - 最新话题
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
AI
AI
C
Cybersecurity and Infrastructure Security Agency CISA
Scott Helme
Scott Helme
PCI Perspectives
PCI Perspectives
S
Securelist
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cyberwarzone
Cyberwarzone
A
Arctic Wolf
Forbes - Security
Forbes - Security
T
Tor Project blog
Spread Privacy
Spread Privacy
WordPress大学
WordPress大学
I
Intezer
Martin Fowler
Martin Fowler
Help Net Security
Help Net Security
P
Proofpoint News Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Cisco Talos Blog
Cisco Talos Blog
Latest news
Latest news
博客园 - 司徒正美
W
WeLiveSecurity
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
V2EX
P
Palo Alto Networks Blog
Google DeepMind News
Google DeepMind News
IT之家
IT之家
阮一峰的网络日志
阮一峰的网络日志
V
Vulnerabilities – Threatpost
Jina AI
Jina AI
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
Simon Willison's Weblog
Simon Willison's Weblog
Project Zero
Project Zero
T
Threatpost
P
Privacy International News Feed
人人都是产品经理
人人都是产品经理
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Apple Machine Learning Research
Apple Machine Learning Research

博客园 - KLAPT

Gateway 网关 CodeX =>Skills Redis 内存满了怎么处理 SpringBoot 默认配置修改 JWT 续签 Access Token + Refresh Token 双 Token claudeCode 命令 MyBatis 的 Mapper 接口 AI | CC GUI 集成 IDEA 完整教程 在IDEA中使用Claude Code IDEA中使用CodeX MyBatisPlus解决大数据量查询慢问题 idea 中的 claude code Token Dubbo 和 Spring Cloud Gateway的区别 Transactional 注解中propagation SpringBoot 快速实现 api 加密 Spring Boot/Cloud 中 bootstrap.yml 与 application.yml SpringBoot 实现 DOCX 转 PDF 微服务Token鉴权设计的几种方案 进程、线程、协程 RSA 加密 Java二维码 ntp服务端和客户端 Chronyd与NTP chronyd 作为服务器时钟 chrony sudo命令和su 的区别 java -cp 和 java -jar Maven 项目打包:实现业务代码与第三方依赖分离 达梦数据库创建用户 梦数据库新增大字段报错问题 达梦数据库操作 MySQL UPDATE多表关联更新 达梦数据库 为HTTP POST请求设置请求体 在Java中调用第三方接口并返回第三方页面 Java调用第三方接口的方法 Nginx 之Rewrite 使用详解 linux 命令 Spring Boot项目中集成Spring Security OAuth2和Apache Shiro
掌握 Spring 框架这 10 个扩展点
KLAPT · 2026-06-01 · via 博客园 - KLAPT

1. 全局异常处理=====》RestControllerAdvice

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public String handleException(Exceptione{
        if (e instanceof ArithmeticException) {
            return"params error";
        }
        if (e instanceof Exception) {
            return"Internal server exception";
        }
        returnnull;
    }
}

只需在 handleException 方法中处理异常情况。

2. 自定义拦截器

与 Spring 拦截器相比,Spring MVC 拦截器可以在内部获取 HttpServletRequest 和 HttpServletResponse 等 Web 对象实例。

Spring MVC 拦截器的顶级接口是:HandlerInterceptor,它包含三个方法:

  • preHandle:在目标方法执行前执行。
  • postHandle:在目标方法执行后执行。
  • afterCompletion:在请求完成时执行。

为了方便起见,在一般情况下,我们通常使用 HandlerInterceptor 接口的实现类 HandlerInterceptorAdapter

如果存在权限认证、日志记录和统计等场景,可以使用此拦截器。

第一步,通过继承 HandlerInterceptorAdapter 类定义一个拦截器:

publicclassAuthInterceptorextendsHandlerInterceptorAdapter{
    @Override
    publicbooleanpreHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
        String requestUrl = request.getRequestURI();
        if (checkAuth(requestUrl)) {
            returntrue;
        }
        returnfalse;
    }

    privatebooleancheckAuth(String requestUrl){
        System.out.println("===Authority Verification===");
        returntrue;
    }
}

第二步,在 Spring 容器中注册此拦截器。

@Configuration
publicclassWebAuthConfigextendsWebMvcConfigurerAdapter{
    @Bean
    public AuthInterceptor getAuthInterceptor(){
        returnnew AuthInterceptor();
    }

    @Override
    publicvoidaddInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new AuthInterceptor());
    }
}

3. 获取 Spring 容器对象

在日常开发中,我们经常需要从 Spring 容器中获取 Beans

3.1 BeanFactoryAware 接口

@Service
publicclassStudentServiceimplementsBeanFactoryAware{
    private BeanFactory beanFactory;

    @Override
    publicvoidsetBeanFactory(BeanFactory beanFactory)throws BeansException {
        this.beanFactory = beanFactory;
    }

    publicvoidadd(){
        Student student = (Student) beanFactory.getBean("student");
    }
}

实现 BeanFactoryAware 接口,然后重写 setBeanFactory 方法。从这个方法中,可以获取 Spring 容器对象。

3.2 ApplicationContextAware 接口

@Service
publicclassStudentService2implementsApplicationContextAware{
    private ApplicationContext applicationContext;

    @Override
    publicvoidsetApplicationContext(ApplicationContext applicationContext)throws BeansException {
        this.applicationContext = applicationContext;
    }

    publicvoidadd(){
        Student student = (Student) applicationContext.getBean("student");
    }
}

4. 导入配置
有时我们需要在某个配置类中导入其他一些类,并且导入的类也会被添加到 Spring 容器中。此时,可以使用@Import 注解来完成此功能。

导入普通类

这种导入方式最简单。导入的类将被实例化为一个 bean 对象。

publicclassA{
}

@Import(A.class)
@Configuration
publicclassTestConfiguration{
}

通过@Import 注解导入类 A,Spring 可以自动实例化对象 A。然后,可以在需要的地方通过@Autowired 注解进行注入:

@Autowired
private A a;

4.2 导入带有@Configuration 注解的配置类

这种导入方式最复杂,因为@Configuration 注解还支持多种组合注解,例如:

  • @Import
  • @ImportResource
  • @PropertySource 等
publicclassA{
}

publicclass B {
}

@Import(B.class)
@Configuration
publicclassAConfiguration{
    @Bean
    public A a(){
        returnnew A();
    }
}

@Import(AConfiguration.class)
@Configuration
publicclassTestConfiguration{
}

通过@Import 注解导入一个带有@Configuration 注解的配置类,与该配置类相关的@Import@ImportResource 和@PropertySource 等注解导入的所有类将一次性全部导入。

4.3 ImportSelector

这种导入方式需要实现 ImportSelector 接口:

publicclassAImportSelectorimplementsImportSelector{
    privatestaticfinal String CLASS_NAME = "com.demo.cache.service.A";

    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        returnnew String[]{CLASS_NAME};
    }
}

@Import(AImportSelector.class)
@Configuration
publicclassTestConfiguration{
}

这种方法的优点是 selectImports 方法返回一个数组,这意味着可以非常方便的导入多个类。

4.4 ImportBeanDefinitionRegistrar

这种导入方式需要实现 ImportBeanDefinitionRegistrar 接口:

publicclassAImportBeanDefinitionRegistrarimplementsImportBeanDefinitionRegistrar{
    @Override
    publicvoidregisterBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry){
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(A.class);
        registry.registerBeanDefinition("a", rootBeanDefinition);
    }
}

@Import(AImportBeanDefinitionRegistrar.class)
@Configuration
publicclassTestConfiguration{
}