Parcourir la source

更新 WebApplicationContext 中 RequestMappingHandlerMapping 实例的获取

reghao il y a 4 mois
Parent
commit
88633e7964

+ 9 - 2
web/src/main/java/cn/reghao/bnt/web/config/spring/SpringLifecycle.java

@@ -17,6 +17,7 @@ import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.DisposableBean;
 import org.springframework.boot.ApplicationArguments;
 import org.springframework.boot.ApplicationRunner;
+import org.springframework.boot.SpringApplication;
 import org.springframework.boot.context.event.ApplicationReadyEvent;
 import org.springframework.context.event.EventListener;
 import org.springframework.core.annotation.Order;
@@ -89,14 +90,20 @@ public class SpringLifecycle implements ApplicationRunner, DisposableBean, Servl
     }
 
     private void initSys() {
-        //initForegroundUrlsPrefix();
+        initForegroundUrlsPrefix();
         builderInit.init();
     }
 
     private void initForegroundUrlsPrefix() {
         foregroundUrlsPrefix.clear();
         String clazzName = ForegroundController.class.getName();
-        RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
+        Object bean = applicationContext.getBean("requestMappingHandlerMapping");
+        if (!(bean instanceof RequestMappingHandlerMapping requestMappingHandlerMapping)) {
+            log.error("Spring 容器中没有 RequestMappingHandlerMapping bean 实例, 结束进程...");
+            System.exit(SpringApplication.exit(applicationContext));
+            return;
+        }
+
         Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
         for (Map.Entry<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodEntry : map.entrySet()) {
             RequestMappingInfo requestMappingInfo = mappingInfoHandlerMethodEntry.getKey();

+ 0 - 97
web/src/test/java/BlogTest.java

@@ -30,101 +30,4 @@ import java.util.stream.Collectors;
 @ActiveProfiles("dev")
 @SpringBootTest(classes = WebApplication.class)
 public class BlogTest {
-    @Autowired
-    UserRepository userRepository;
-    @Autowired
-    private PasswordEncoder passwordEncoder;
-    public void updatePassword() {
-        int userId = 1;
-        User user = userRepository.findById(userId).orElse(null);
-        if (user == null) {
-            return;
-        }
-
-        String newPassword = "admin123456";
-        String newSalt = RandomString.getSalt(64);
-        String encodedNewPasswd = passwordEncoder.encode(newPassword + newSalt);
-
-        user.setEncodedPassword(encodedNewPasswd);
-        user.setSalt(newSalt);
-        userRepository.save(user);
-    }
-
-    @Autowired
-    WebApplicationContext applicationContext;
-    @Test
-    public void getAllUrlsTest() {
-        List<Map<String, String>> resList = new ArrayList<>();
-        RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
-        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
-        for (Map.Entry<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodEntry : map.entrySet()) {
-            Map<String, String> resultMap = new LinkedHashMap<>();
-            RequestMappingInfo requestMappingInfo = mappingInfoHandlerMethodEntry.getKey();
-            HandlerMethod handlerMethod = mappingInfoHandlerMethodEntry.getValue();
-            resultMap.put("className", handlerMethod.getMethod().getDeclaringClass().getName());
-            Annotation[] declaredAnnotations = handlerMethod.getMethod().getDeclaredAnnotations();
-
-            /*Annotation[] parentAnnotations = handlerMethod.getBeanType().getAnnotations();
-            for (Annotation annotation : parentAnnotations) {
-                if (annotation instanceof Api) {
-                    Api api = (Api) annotation;
-                    resultMap.put("classDesc", api.value());
-                } else if (annotation instanceof RequestMapping) {
-                    RequestMapping requestMapping = (RequestMapping) annotation;
-                    if (null != requestMapping.value() && requestMapping.value().length > 0) {
-                        resultMap.put("classURL", requestMapping.value()[0]);
-                    }
-                }
-            }*/
-            resultMap.put("methodName", handlerMethod.getMethod().getName());
-            /*Annotation[] annotations = handlerMethod.getMethod().getDeclaredAnnotations();
-            if (annotations != null) {
-                for (Annotation annotation : annotations) {
-                    if (annotation instanceof ApiOperation) {
-                        ApiOperation methodDesc = (ApiOperation) annotation;
-                        String desc = methodDesc.value();
-                        resultMap.put("methodDesc", desc);
-                    }
-                }
-            }*/
-
-            PatternsRequestCondition p = requestMappingInfo.getPatternsCondition();
-            for (String url : p.getPatterns()) {
-                resultMap.put("methodURL", url);
-            }
-
-            RequestMethodsRequestCondition methodsRequestCondition = requestMappingInfo.getMethodsCondition();
-            for (RequestMethod requestMethod : methodsRequestCondition.getMethods()) {
-                resultMap.put("requestType", requestMethod.toString());
-            }
-
-            resList.add(resultMap);
-        }
-
-        List<ReqUrl> list = map.keySet().stream().map(requestMappingInfo -> {
-            List<String> list1 = new ArrayList<>(requestMappingInfo.getPatternsCondition().getPatterns());
-            List<RequestMethod> list2 = new ArrayList<>(requestMappingInfo.getMethodsCondition().getMethods());
-            String url = list1.get(0);
-            if (url.equals("/error") || url.startsWith("/swagger")) {
-                return null;
-            }
-
-            String method = list2.get(0).name();
-            return new ReqUrl(method, url);
-        }).filter(Objects::nonNull).collect(Collectors.toList());
-
-        System.out.println();
-    }
-
-    @AllArgsConstructor
-    @Getter
-    static class ReqUrl {
-        private String method;
-        private String url;
-
-        @Override
-        public String toString() {
-            return url;
-        }
-    }
 }

+ 114 - 2
web/src/test/java/RbacTest.java

@@ -2,16 +2,21 @@ import cn.reghao.bnt.web.WebApplication;
 import cn.reghao.bnt.web.admin.controller.LoginController;
 import cn.reghao.bnt.web.admin.db.repository.MenuRepository;
 import cn.reghao.bnt.web.admin.db.repository.RoleRepository;
+import cn.reghao.bnt.web.admin.db.repository.UserRepository;
 import cn.reghao.bnt.web.admin.model.constant.MenuType;
 import cn.reghao.bnt.web.admin.model.constant.RoleType;
 import cn.reghao.bnt.web.admin.model.po.Menu;
 import cn.reghao.bnt.web.admin.model.po.Role;
+import cn.reghao.bnt.web.admin.model.po.User;
 import cn.reghao.bnt.web.admin.service.AccountService;
 import cn.reghao.bnt.web.admin.service.AccountSessionService;
 import cn.reghao.bnt.web.admin.service.MenuService;
 import cn.reghao.bnt.web.blog.controller.ForegroundController;
 import cn.reghao.bnt.web.config.web.exception.ControllerErrorHandler;
+import cn.reghao.jutil.jdk.security.RandomString;
 import io.swagger.v3.oas.annotations.Operation;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
 import lombok.extern.slf4j.Slf4j;
 import org.junit.jupiter.api.Test;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -20,6 +25,7 @@ import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebSe
 import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
 import org.springframework.context.ApplicationContext;
 import org.springframework.data.domain.PageRequest;
+import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.session.jdbc.JdbcIndexedSessionRepository;
 import org.springframework.test.context.ActiveProfiles;
 import org.springframework.web.bind.annotation.PostMapping;
@@ -27,6 +33,8 @@ import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.context.WebApplicationContext;
 import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
+import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
 import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
 import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
 
@@ -43,6 +51,26 @@ import java.util.stream.Collectors;
 @ActiveProfiles("dev")
 @SpringBootTest(classes = WebApplication.class)
 public class RbacTest {
+    @Autowired
+    UserRepository userRepository;
+    @Autowired
+    private PasswordEncoder passwordEncoder;
+    public void updatePassword() {
+        int userId = 1;
+        User user = userRepository.findById(userId).orElse(null);
+        if (user == null) {
+            return;
+        }
+
+        String newPassword = "admin123456";
+        String newSalt = RandomString.getSalt(64);
+        String encodedNewPasswd = passwordEncoder.encode(newPassword + newSalt);
+
+        user.setEncodedPassword(encodedNewPasswd);
+        user.setSalt(newSalt);
+        userRepository.save(user);
+    }
+
     @Autowired
     MenuService menuService;
     @Autowired
@@ -56,9 +84,13 @@ public class RbacTest {
                 .collect(Collectors.groupingBy(Menu::getUrl,
                         Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0))));
 
+        Object bean = applicationContext.getBean("requestMappingHandlerMapping");
+        if (!(bean instanceof RequestMappingHandlerMapping requestMappingHandlerMapping)) {
+            return;
+        }
+
         Set<String> allUrls = new HashSet<>();
-        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
-        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
+        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
         for (Map.Entry<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodEntry : map.entrySet()) {
             RequestMappingInfo requestMappingInfo = mappingInfoHandlerMethodEntry.getKey();
             HandlerMethod handlerMethod = mappingInfoHandlerMethodEntry.getValue();
@@ -160,6 +192,86 @@ public class RbacTest {
         }
     }
 
+    @Test
+    public void getAllUrlsTest() {
+        List<Map<String, String>> resList = new ArrayList<>();
+        Object bean = applicationContext.getBean("requestMappingHandlerMapping");
+        if (!(bean instanceof RequestMappingHandlerMapping requestMappingHandlerMapping)) {
+            return;
+        }
+
+        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
+        for (Map.Entry<RequestMappingInfo, HandlerMethod> mappingInfoHandlerMethodEntry : map.entrySet()) {
+            Map<String, String> resultMap = new LinkedHashMap<>();
+            RequestMappingInfo requestMappingInfo = mappingInfoHandlerMethodEntry.getKey();
+            HandlerMethod handlerMethod = mappingInfoHandlerMethodEntry.getValue();
+            resultMap.put("className", handlerMethod.getMethod().getDeclaringClass().getName());
+            Annotation[] declaredAnnotations = handlerMethod.getMethod().getDeclaredAnnotations();
+
+            /*Annotation[] parentAnnotations = handlerMethod.getBeanType().getAnnotations();
+            for (Annotation annotation : parentAnnotations) {
+                if (annotation instanceof Api) {
+                    Api api = (Api) annotation;
+                    resultMap.put("classDesc", api.value());
+                } else if (annotation instanceof RequestMapping) {
+                    RequestMapping requestMapping = (RequestMapping) annotation;
+                    if (null != requestMapping.value() && requestMapping.value().length > 0) {
+                        resultMap.put("classURL", requestMapping.value()[0]);
+                    }
+                }
+            }*/
+            resultMap.put("methodName", handlerMethod.getMethod().getName());
+            /*Annotation[] annotations = handlerMethod.getMethod().getDeclaredAnnotations();
+            if (annotations != null) {
+                for (Annotation annotation : annotations) {
+                    if (annotation instanceof ApiOperation) {
+                        ApiOperation methodDesc = (ApiOperation) annotation;
+                        String desc = methodDesc.value();
+                        resultMap.put("methodDesc", desc);
+                    }
+                }
+            }*/
+
+            PatternsRequestCondition p = requestMappingInfo.getPatternsCondition();
+            for (String url : p.getPatterns()) {
+                resultMap.put("methodURL", url);
+            }
+
+            RequestMethodsRequestCondition methodsRequestCondition = requestMappingInfo.getMethodsCondition();
+            for (RequestMethod requestMethod : methodsRequestCondition.getMethods()) {
+                resultMap.put("requestType", requestMethod.toString());
+            }
+
+            resList.add(resultMap);
+        }
+
+        List<ReqUrl> list = map.keySet().stream().map(requestMappingInfo -> {
+            List<String> list1 = new ArrayList<>(requestMappingInfo.getPatternsCondition().getPatterns());
+            List<RequestMethod> list2 = new ArrayList<>(requestMappingInfo.getMethodsCondition().getMethods());
+            String url = list1.get(0);
+            if (url.equals("/error") || url.startsWith("/swagger")) {
+                return null;
+            }
+
+            String method = list2.get(0).name();
+            return new ReqUrl(method, url);
+        }).filter(Objects::nonNull).collect(Collectors.toList());
+
+        System.out.println();
+    }
+
+    @AllArgsConstructor
+    @Getter
+    static class ReqUrl {
+        private String method;
+        private String url;
+
+        @Override
+        public String toString() {
+            return url;
+        }
+    }
+
     @Autowired
     JdbcIndexedSessionRepository sessionRepository;
     @Autowired