springboot怎么手动动态注入controller和service

springboot怎么手动动态注入controller和service

这篇文章主要介绍“springboot怎么手动动态注入controller和service”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“springboot怎么手动动态注入controller和service”文章能帮助大家解决问题。

手动动态注入controller和service

packagetest;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.config.BeanDefinition;importorg.springframework.beans.factory.support.BeanDefinitionBuilder;importorg.springframework.beans.factory.support.DefaultListableBeanFactory;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.context.ApplicationContext;importorg.springframework.context.ConfigurableApplicationContext;importorg.springframework.core.io.FileSystemResource;importorg.springframework.core.io.FileSystemResourceLoader;importorg.springframework.stereotype.Component;importorg.springframework.util.ClassUtils;importorg.springframework.util.ReflectionUtils;importorg.springframework.util.StringUtils;importorg.springframework.web.servlet.mvc.method.RequestMappingInfo;importorg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.net.MalformedURLException;importjava.net.URL;importjava.net.URLClassLoader;@SpringBootApplication@ComponentpublicclassApplicationBootstrap{staticApplicationContextapplicationContext;staticStringfile="F:\\download\\apache-maven-3.3.9-bin\\repository\\org\\example\\springboot-test-common\\1.0-SNAPSHOT\\"+"springboot-test-common-1.0-SNAPSHOT.jar";publicstaticvoidmain(String[]args)throwsException{applicationContext=SpringApplication.run(ApplicationBootstrap.class,args);StringclazzName="test1.controller.MyTestController1";StringclazzName1="test1.service.MyTestServiceImpl";registerBean(clazzName1);registerBean(clazzName);registerController(StringUtils.uncapitalize(clazzName.substring(clazzName.lastIndexOf(".")+1)));}publicstaticvoidregisterBean(StringclazzName)throwsException{URLurl=newFile(file).toURI().toURL();//URLClassLoaderloader=(URLClassLoader)ApplicationBootstrap.class.getClassLoader();//Methodadd=URLClassLoader.class.getDeclaredMethod("addURL",newClass[]{URL.class});//add.setAccessible(true);//add.invoke(loader,url);URLClassLoaderloader=newURLClassLoader(newURL[]{url});//StringclazzName="test1.controller.MyTestController1";Class<?>clazz=loader.loadClass(clazzName);//applicationContext.getClassLoader().loadClass("test.MyController");//DefaultListableBeanFactoryfactory=(DefaultListableBeanFactory)applicationContext.getAutowireCapableBeanFactory();BeanDefinitionBuilderbeanDefinitionBuilder=BeanDefinitionBuilder.genericBeanDefinition(clazz);BeanDefinitionbeanDefinition=beanDefinitionBuilder.getRawBeanDefinition();//设置当前bean定义对象是单利的beanDefinition.setScope("singleton");//将变量首字母置小写StringbeanName=StringUtils.uncapitalize(clazzName);beanName=beanName.substring(beanName.lastIndexOf(".")+1);beanName=StringUtils.uncapitalize(beanName);//将applicationContext转换为ConfigurableApplicationContextConfigurableApplicationContextconfigurableApplicationContext=(ConfigurableApplicationContext)applicationContext;//获取bean工厂并转换为DefaultListableBeanFactoryDefaultListableBeanFactorydefaultListableBeanFactory=(DefaultListableBeanFactory)configurableApplicationContext.getBeanFactory();defaultListableBeanFactory.registerBeanDefinition(beanName,beanDefinition);}/***注册Controller*@paramcontrollerBeanName*@throwsException*/publicstaticvoidregisterController(StringcontrollerBeanName)throwsException{finalRequestMappingHandlerMappingrequestMappingHandlerMapping=applicationContext.getBean(RequestMappingHandlerMapping.class);if(requestMappingHandlerMapping!=null){Stringhandler=controllerBeanName;Objectcontroller=applicationContext.getBean(handler);if(controller==null){return;}//unregisterController(controllerBeanName);//注册ControllerMethodmethod=requestMappingHandlerMapping.getClass().getSuperclass().getSuperclass().getDeclaredMethod("detectHandlerMethods",Object.class);//将private改为可使用method.setAccessible(true);method.invoke(requestMappingHandlerMapping,handler);}}/***去掉Controller的Mapping*@paramcontrollerBeanName*/publicstaticvoidunregisterController(StringcontrollerBeanName){finalRequestMappingHandlerMappingrequestMappingHandlerMapping=(RequestMappingHandlerMapping)applicationContext.getBean("requestMappingHandlerMapping");if(requestMappingHandlerMapping!=null){Stringhandler=controllerBeanName;Objectcontroller=applicationContext.getBean(handler);if(controller==null){return;}finalClass<?>targetClass=controller.getClass();ReflectionUtils.doWithMethods(targetClass,newReflectionUtils.MethodCallback(){publicvoiddoWith(Methodmethod){MethodspecificMethod=ClassUtils.getMostSpecificMethod(method,targetClass);try{MethodcreateMappingMethod=RequestMappingHandlerMapping.class.getDeclaredMethod("getMappingForMethod",Method.class,Class.class);createMappingMethod.setAccessible(true);RequestMappingInforequestMappingInfo=(RequestMappingInfo)createMappingMethod.invoke(requestMappingHandlerMapping,specificMethod,targetClass);if(requestMappingInfo!=null){requestMappingHandlerMapping.unregisterMapping(requestMappingInfo);}}catch(Exceptione){e.printStackTrace();}}},ReflectionUtils.USER_DECLARED_METHODS);}}}

在controller中使用参数

说明

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

springboot怎么手动动态注入controller和service

packagecom.mzj.springboot.actionpai.controller;importcom.mzj.springboot.actionpai.common.User;importorg.springframework.web.bind.annotation.*;importjavax.servlet.http.HttpServletRequest;importjava.util.List;@RestControllerpublicclassHelloWorldController3{//----------------------方法1、获取路径中的值----------------------------/***URL:http://localhost:8081/addUser0/MAZHONGJIA**@paramusername*@return*/@GetMapping("/addUser0/{username}")publicStringaddUser0(@PathVariableStringusername){System.out.println("username:"+username);return"success0";}//----------------------方法2、获取路径中的参数----------------------------/***URL:http://localhost:8081/addUser1?username=mazhongjia**@paramusername*@return*/@GetMapping("/addUser1")publicStringaddUser1(Stringusername){System.out.println("username:"+username);return"success1";}//----------------------方法3、通过bean接收HTTP提交的对象----------------------------/***URL:http://localhost:8081/addUser2?username=mazhongjia&age=33**@paramuser*@return*/@GetMapping("/addUser2")publicStringaddUser2(Useruser){System.out.println("user..."+user);return"success2";}//----------------------方法4、通过HttpServletRequest接收参数----------------------------/***URL:http://localhost:8081/addUser3?username=mazhongjia**@paramrequest*@return*/@GetMapping("/addUser3")publicStringaddUser3(HttpServletRequestrequest){System.out.println("username..."+request.getParameter("username"));return"success3";}//----------------------方法5、用@RequestParam绑定入参----------------------------/***通过@RequestParam注解绑定入参*<p>*URL:http://localhost:8081/addUser1?username=mazhongjia**@paramusername*@return*/@GetMapping("/addUser4")publicStringaddUser4(@RequestParamStringusername){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】**@paramuserList*@return*/@PostMapping("/addUser5")publicStringaddUser5(@RequestBodyList<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参数中取值**@paramuser*@return*/@PostMapping("/addUser6")publicStringaddUser6(@ModelAttribute("user")Useruser){System.out.println("user..."+user);return"success6";}/***URL:http://localhost:8081/addUser7*<p>*通过@ModelAttribute注解,从Model、Form或者URL请求参数中获取属性值,上面的URL演示从Model中取值**@paramuser*@return*/@PostMapping("/addUser7")publicStringaddUser7(@ModelAttribute("user")Useruser){System.out.println("user7..."+user);return"success7";}@ModelAttribute("user")publicUseraddAccount(){returnnewUser("jz",55);}}

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

关于“springboot怎么手动动态注入controller和service”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注恰卡编程网行业资讯频道,小编每天都会为大家更新不同的知识点。

发布于 2022-03-18 22:47:47
收藏
分享
海报
0 条评论
31
上一篇:Java的布隆过滤器如何实现 下一篇:基于C++如何实现信息管理系统
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码