服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - springboot手动动态注入controller和service方式

springboot手动动态注入controller和service方式

2022-10-09 14:12JustPlay1994 Java教程

这篇文章主要介绍了springboot手动动态注入controller和service方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

手动动态注入controller和service

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
@SpringBootApplication
@Component
public class ApplicationBootstrap {
    static ApplicationContext applicationContext;
    static String file = "F:\\download\\apache-maven-3.3.9-bin\\repository\\org\\example\\springboot-test-common\\1.0-SNAPSHOT\\" +
            "springboot-test-common-1.0-SNAPSHOT.jar";
    public static void main(String[] args) throws Exception {
        applicationContext = SpringApplication.run(ApplicationBootstrap.class, args);
        String clazzName = "test1.controller.MyTestController1";
        String clazzName1 = "test1.service.MyTestServiceImpl";
        registerBean(clazzName1);
        registerBean(clazzName);
        registerController(StringUtils.uncapitalize(clazzName.substring(clazzName.lastIndexOf(".") + 1)));
    }
    public static void registerBean(String clazzName) throws Exception{
        URL url = new File(file).toURI().toURL();
//        URLClassLoader loader = (URLClassLoader) ApplicationBootstrap.class.getClassLoader();
//        Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
//        add.setAccessible(true);
//        add.invoke(loader, url);
        URLClassLoader loader = new URLClassLoader(new URL[]{url});
//        String clazzName = "test1.controller.MyTestController1";
        Class<?> clazz = loader.loadClass(clazzName);
//        applicationContext.getClassLoader().loadClass("test.MyController");
//        DefaultListableBeanFactory factory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
        //设置当前bean定义对象是单利的
        beanDefinition.setScope("singleton");
        //将变量首字母置小写
        String beanName = StringUtils.uncapitalize(clazzName);
        beanName =  beanName.substring(beanName.lastIndexOf(".")+1);
        beanName = StringUtils.uncapitalize(beanName);
        //将applicationContext转换为ConfigurableApplicationContext
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        // 获取bean工厂并转换为DefaultListableBeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
        defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinition);
    }
    /**
     * 注册Controller
     * @param controllerBeanName
     * @throws Exception
     */
    public static void registerController(String controllerBeanName) throws Exception{
        final RequestMappingHandlerMapping requestMappingHandlerMapping=
                applicationContext.getBean(RequestMappingHandlerMapping.class);
        if(requestMappingHandlerMapping!=null){
            String handler=controllerBeanName;
            Object controller= applicationContext.getBean(handler);
            if(controller==null){
                return;
            }
//            unregisterController(controllerBeanName);
            //注册Controller
            Method method=requestMappingHandlerMapping.getClass().getSuperclass().getSuperclass().
                    getDeclaredMethod("detectHandlerMethods",Object.class);
            //将private改为可使用
            method.setAccessible(true);
            method.invoke(requestMappingHandlerMapping,handler);
        }
    }
    /**
     * 去掉Controller的Mapping
     * @param controllerBeanName
     */
    public static void unregisterController(String controllerBeanName){
        final RequestMappingHandlerMapping requestMappingHandlerMapping=(RequestMappingHandlerMapping)
                applicationContext.getBean("requestMappingHandlerMapping");
        if(requestMappingHandlerMapping!=null){
            String handler=controllerBeanName;
            Object controller= applicationContext.getBean(handler);
            if(controller==null){
                return;
            }
            final Class<?> targetClass=controller.getClass();
            ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
                public void doWith(Method method) {
                    Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
                    try {
                        Method createMappingMethod = RequestMappingHandlerMapping.class.
                                getDeclaredMethod("getMappingForMethod", Method.class, Class.class);
                        createMappingMethod.setAccessible(true);
                        RequestMappingInfo requestMappingInfo =(RequestMappingInfo)
                                createMappingMethod.invoke(requestMappingHandlerMapping,specificMethod,targetClass);
                        if(requestMappingInfo != null) {
                            requestMappingHandlerMapping.unregisterMapping(requestMappingInfo);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }, ReflectionUtils.USER_DECLARED_METHODS);
        }
    }
}

在controller中使用参数

说明

控制器中使用参数有很多种方式,直接上代码,在代码注释中进行说明

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package com.mzj.springboot.actionpai.controller; 
import com.mzj.springboot.actionpai.common.User;
import org.springframework.web.bind.annotation.*;
 
import javax.servlet.http.HttpServletRequest;
import java.util.List;
 
@RestController
public class HelloWorldController3 {
 
    //----------------------方法1、获取路径中的值----------------------------
    /**
     * URL:http://localhost:8081/addUser0/MAZHONGJIA
     *
     * @param username
     * @return
     */
    @GetMapping("/addUser0/{username}")
    public String addUser0(@PathVariable String username) {
        System.out.println("username : " + username);
        return "success0";
    }
 
    //----------------------方法2、获取路径中的参数----------------------------
    /**
     * URL:http://localhost:8081/addUser1?username=mazhongjia
     *
     * @param username
     * @return
     */
    @GetMapping("/addUser1")
    public String addUser1(String username) {
        System.out.println("username : " + username);
        return "success1";
    }
 
    //----------------------方法3、通过bean接收HTTP提交的对象----------------------------
    /**
     * URL:http://localhost:8081/addUser2?username=mazhongjia&age=33
     *
     * @param user
     * @return
     */
    @GetMapping("/addUser2")
    public String addUser2(User user) {
        System.out.println("user ... " + user);
        return "success2";
    }
 
    //----------------------方法4、通过HttpServletRequest接收参数----------------------------
    /**
     * URL:http://localhost:8081/addUser3?username=mazhongjia
     *
     * @param request
     * @return
     */
    @GetMapping("/addUser3")
    public String addUser3(HttpServletRequest request) {
        System.out.println("username ... " + request.getParameter("username"));
        return "success3";
    }
 
    //----------------------方法5、用@RequestParam绑定入参----------------------------
    /**
     * 通过@RequestParam注解绑定入参
     * <p>
     * URL:http://localhost:8081/addUser1?username=mazhongjia
     *
     * @param username
     * @return
     */
    @GetMapping("/addUser4")
    public String addUser4(@RequestParam String username) {
        System.out.println("username : " + username);
        return "success4";
    }
 
    //----------------------方法6、用@RequestBody接收JSON数据----------------------------
    /**
     * URL:http://localhost:8081/addUser5
     * BODY:
     * [
     * {
     * "username": "mazhongjia",
     * "age": "35"
     * },
     * {
     * "username": "huan",
     * "age": "31"
     * }
     * ]
     * <p>
     * 通过@RequestBody接收JSON入参,同时需要设置http的header中Content-Type属性值为【application/json;charset=UTF-8】
     *
     * @param userList
     * @return
     */
    @PostMapping("/addUser5")
    public String addUser5(@RequestBody List<User> userList) {
        System.out.println("userList : " + userList);
        return "success5";
    }
 
    //----------------------方法7、用@ModelAttribute注解获取参数----------------------------
    /**
     * URL:http://localhost:8081/addUser6?username=mazhong&age=35
     * <p>
     * 通过@ModelAttribute注解,从Model、Form或者URL请求参数中获取属性值,上面的URL演示从URL参数中取值
     *
     * @param user
     * @return
     */
    @PostMapping("/addUser6")
    public String addUser6(@ModelAttribute("user") User user) {
        System.out.println("user ... " + user);
        return "success6";
    }
 
    /**
     * URL:http://localhost:8081/addUser7
     * <p>
     * 通过@ModelAttribute注解,从Model、Form或者URL请求参数中获取属性值,上面的URL演示从Model中取值
     *
     * @param user
     * @return
     */
    @PostMapping("/addUser7")
    public String addUser7(@ModelAttribute("user") User user) {
        System.out.println("user7 ... " + user);
        return "success7";
    }
    @ModelAttribute("user")
    public User addAccount() {
        return new User("jz", 55);
   
}

除了上面的方式外,还有:上传文件MultipartFile、上传图片,这里省略。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u013014636/article/details/106314798

延伸 · 阅读

精彩推荐