解决注解初始化逻辑不自动执行问题

This commit is contained in:
白茶清欢 2025-06-03 16:08:52 +08:00
parent 3d6f322da5
commit 61402bfac7
3 changed files with 44 additions and 2 deletions

9
README.md Normal file
View File

@ -0,0 +1,9 @@
# 使用方式
在主入口函数增加如下注解:
```bash
@Import(value = { cn.zhangdeman.HashMapCache.class}) // 让SpringBoot能够扫描到相关组件
```
会自动扫描自定义的异常注解, 并进行数据初始化

View File

@ -24,6 +24,12 @@
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -1,6 +1,9 @@
package cn.zhangdeman;
import cn.zhangdeman.annotation.CustomExceptionScanAnnotation;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ClassUtils;
@ -12,16 +15,18 @@ import java.util.*;
// 基于hashmap实现的内存缓存
// 因为就是服务启动时初始化一次, 无需考虑多线程并发安全问题
public class HashMapCache {
public class HashMapCache implements ServletContextListener {
// 单例: 饿汉模式
private static final HashMapCache hashMapCache = new HashMapCache();
private final Map<Object, String> cache = new HashMap<>();
@Autowired
private ApplicationContext applicationContext;
//将构造器设置为private禁止通过new进行实例化
private HashMapCache() {
}
// 此处实现的是自定义注解的解析逻辑, 将错误码全部加载到内存中
public void loadCustomException(ApplicationContext applicationContext) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
public void loadCustomException() throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
Map<String, Object> customExceptionScanAnnotationMap = applicationContext.getBeansWithAnnotation(CustomExceptionScanAnnotation.class);
for(Object bean : customExceptionScanAnnotationMap.values()){
Class<?> extensionClz = ClassUtils.getUserClass(bean);
@ -117,4 +122,26 @@ public class HashMapCache {
}
return classList;
}
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("包内自动触发初始化" + new Date());
try {
this.loadCustomException();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}