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中使用参数
说明
控制器中使用参数有很多种方式,直接上代码,在代码注释中进行说明
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”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注恰卡编程网行业资讯频道,小编每天都会为大家更新不同的知识点。
推荐阅读
-
vue动态添加删除输入框(springboot vue怎么让数据库显示出来)
springbootvue怎么让数据库显示出来?一般情况下是前端调阅后端接口,来获取到数据库的数据,后端哪里会把数据库的数据整理...
-
php 一步步实现mvc架构——路由篇
-
「php」thinkphp5实战(一):界面引入
-
springboot实现基于aop的切面日志
本文实例为大家分享了springboot实现基于aop的切面日志的具体代码,供大家参考,具体内容如下通过aop的切面方式实现日志...
-
SpringBoot定时任务功能怎么实现
-
SpringBoot中的@Import注解怎么使用
-
SpringBoot整合Lombok及常见问题怎么解决
-
Angular怎么利用service实现自定义服务
-
springboot图片验证码功能模块怎么实现
-
Springboot+SpringSecurity怎么实现图片验证码登录