In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how Springboot injects Service or mapper into common types". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to inject Service or mapper into a common type by Springboot.
Springboot injects Service or mapper into a normal type
Recently encountered a difficult problem (the boss may think this is too easy), for a rookie like me, it is really a bit of a headache.
Next, to talk about the problem I encountered, a UDP client was created in spring boot to listen for data sent to the UDP server. There are two main difficulties in realizing this function.
1. Because previously, the service layer was called through controller to achieve access.
Now it is necessary to establish a lasting connection to monitor the data of a certain port, which has been bothered for a long time because of not many projects, lack of experience, and little learning from spring.
Simply opening a thread to create an instance of new in the main method solves the problem. I don't know if this is the right thing to do, but it works. (if there is a better way, please tell Xiaobai, thank you)
@ SpringBootApplication@MapperScan ("com.example.net.udpservicertest.mapper") public class UdpServicerTestApplication {public static void main (String [] args) throws Exception {SpringApplication.run (UdpServicerTestApplication.class, args); new Thread ()-> {try {UDPService udpService = new UDPService (); udpService.startSocketServer ();} catch (Exception e) {e.printStackTrace () }) .start ();}}
Although the client can be started, a new problem arises.
two。 After getting the data, a null pointer appears when service is dropped
This has perplexed rookies for another two days, and this solution has been obtained through this article.
(1) first, you need to create a new class to implement the ApplicationContextAware interface.
To @ Conponment comment
@ Component public class SpringUtils implements ApplicationContextAware {private static ApplicationContext applicationContext = null; @ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {if (SpringUtils.applicationContext = = null) {SpringUtils.applicationContext = applicationContext }} / / get applicationContext public static ApplicationContext getApplicationContext () {return applicationContext;} / / get Bean through name. Public static Object getBean (String name) {return getApplicationContext (). GetBean (name);} / / get Bean through class. Public static T getBean (Class clazz) {return getApplicationContext () .getBean (clazz);} / / return the specified Bean public static T getBean (String name,Class clazz) {return getApplicationContext () .getBean (name, clazz) through name and Clazz;}}
(2) get the ApplicationContext object in the UDP class, and then get the service or dao you need.
The @ Service annotation automatically registers to the Spring container, eliminating the need to define bean in the applicationContext.xml file. Similar annotations include @ Component, @ Repository, and @ Controller.
ApplicationContext is also a container for spring-managed bean, and when the configuration file is loaded, all the classes managed by Spring are instantiated. So it can be injected into the instance.
Public class UDPService {private ApplicationContext applicationContext=SpringUtils.getApplicationContext (); private UserServiceImpl userService=applicationContext.getBean (UserServiceImpl.class); public void startSocketServer () throws Exception {DatagramSocket ds = new DatagramSocket (10000); while (true) {/ / 2. Create packet byte [] buf = new byte [1024]; DatagramPacket dp = new DatagramPacket (buf, buf.length); / / 3. Use the accept method to store the data in the packet ds.receive (dp); / / blocking / / 4. Through the method of packet object, parse the data content / / String ip = dp.getAddress (). GetHostAddress (); / / int port = dp.getPort (); String text = new String (dp.getData (), 0, dp.getLength ()); System.out.println ("" + text.length ()); System.out.println ("" + text) / / byte [] data = dp.getData (); String [] split = text.split ("#"); System.out.println (split [0]); userService.updateUser (split [0], split [1]); Thread.sleep (3000L) }} @ SpringBootApplication@MapperScan ("com.example.net.udpservicertest.mapper") @ ComponentScan ("com.example.net.udpservicertest") public class UdpServicerTestApplication {public static void main (String [] args) throws Exception {SpringApplication.run (UdpServicerTestApplication.class, args); new Thread ()-> {try {UDPService udpService = new UDPService (); udpService.startSocketServer () } catch (Exception e) {e.printStackTrace ();}}) .start ();}}
The headache problem has finally been solved! Happy ~
How to use injection in springboot normal classes
A custom method is required:
Package com.example.demo.util;import org.springframework.beans.BeansException;import org.springframework.beans.factory.NoSuchBeanDefinitionException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component / * * @ author Mikey * @ Title: * @ Description: you can also use Bean * @ Email:1625017540@qq.com * @ date 21:57 on 2018-12-3 * @ Version 1.0 * / @ Componentpublic class SpringUtil implements ApplicationContextAware {private static ApplicationContext applicationContext = null; public SpringUtil () {} public void setApplicationContext (ApplicationContext arg0) throws BeansException {if (applicationContext = = null) {applicationContext = arg0 }} public static ApplicationContext getApplicationContext () {return applicationContext;} public static void setAppCtx (ApplicationContext webAppCtx) {if (webAppCtx! = null) {applicationContext = webAppCtx }} / * after getting the ApplicationContext object instance, you can manually obtain the Bean injection instance object * / public static T getBean (Class clazz) {return getApplicationContext () .getBean (clazz);} public static T getBean (String name, Class clazz) throws ClassNotFoundException {return getApplicationContext () .getBean (name, clazz) } public static final Object getBean (String beanName) {return getApplicationContext (). GetBean (beanName);} public static final Object getBean (String beanName, String className) throws ClassNotFoundException {Class clz = Class.forName (className); return getApplicationContext (). GetBean (beanName, clz.getClass ());} public static boolean containsBean (String name) {return getApplicationContext (). ContainsBean (name) } public static boolean isSingleton (String name) throws NoSuchBeanDefinitionException {return getApplicationContext () .isSingleton (name);} public static Class getType (String name) throws NoSuchBeanDefinitionException {return getApplicationContext () .getType (name);} public static String [] getAliases (String name) throws NoSuchBeanDefinitionException {return getApplicationContext (). GetAliases (name);}}
Use:
Package com.example.demo.util;import com.example.demo.Controller.login.JwtAuthenticator;import com.example.demo.Dao.userandroleandpermissionDao.HRUserDao;import com.example.demo.Entity.userandroleandpermission.HRUser;import org.apache.shiro.SecurityUtils;import org.apache.shiro.subject.Subject;public class MethodUtils {public HRUser findUserByToken () {Subject subject = SecurityUtils.getSubject (); String token = subject.getPrincipal () .toString (); String code = JwtAuthenticator.getUsername (token) HRUserDao hrUserDao = SpringUtil.getBean (HRUserDao.class); / / here we get bean HRUser user = hrUserDao.findByCode (code) according to class .class; if (user! = null) {return user;} else {return null;} so far, I believe you have a better understanding of "how Springboot injects Service or mapper into common types". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.