Springboot injects Service or mapper in common type

  • 2021-12-12 08:25:48
  • OfStack

Directory Springboot injects Service or mapper1 in common type. Since controller calls service layer to realize access before. 2. After getting data, when dropping service, null pointer appears. How does springboot common class use injection

Springboot injects Service or mapper in common type

Recently, I encountered a difficult problem (bosses may feel that this is too simple). For a small white like me, I really have some headaches.

Let's talk about the problem I encountered. I created an UDP client in spring boot to listen to the data sent by UDP server. There are two main difficulties encountered when implementing this 1 function

1. Because the service layer was called through controller before, the access was realized

Now to establish a durable connection to monitor the data of a port 1, due to the project is not much, lack of experience, spring also not how to learn so troubled for a long time.

Just open a thread in the main method to create a simple new instance to solve this problem. Although I don't know if this is right, it can realize the function. (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 start, a new problem comes again

2. After getting the data, a null pointer appears when service is dropped

This puzzled Xiaobai for two days, and got such a solution through this article

(1) First, you need to create a new class to implement the ApplicationContextAware interface.

To @ Conponment annotation


   @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;
            }
 
            // Pass name Get  Bean.
            public static Object getBean(String name){
                return getApplicationContext().getBean(name);
            }
 
            // Pass class Get Bean.
            public static <T> T getBean(Class<T> clazz){
                return getApplicationContext().getBean(clazz);
            }
 
            // Pass name, As well as Clazz Returns the specified Bean
            public static <T> T getBean(String name,Class<T> clazz){
                return getApplicationContext().getBean(name, clazz);
            }
        }

(2) Get the ApplicationContext object in the UDP class, and then get the required service or dao.

The @ Service annotation will automatically register with the Spring container, and there is no need to define bean in the applicationContext. xml file. Similar ones include @ Component, @ Repository and @ Controller.

ApplicationContext is the container for spring to manage bean. When the configuration file is loaded, all the classes managed by Spring will be instantiated. So it can be injected into this 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 a package 
            byte[] buf = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buf, buf.length);
 
            // 3. Use the accept method to store data in a packet 
            ds.receive(dp);//  Blocking type 
 
            // 4. Parse the data through the method of packet object   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 has finally been solved! Happy ~

How does the springboot common class use injection

Custom methods are 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: Used for ordinary classes can also be used Bean
 * @Email:1625017540@qq.com
 * @date 2018/12/3 21:57
 * @Version 1.0
 */
@Component
public 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;
        }
    }
    /**
     *  Get ApplicationContext Object instance, you can manually get the Bean Injection instance object of 
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
    public static <T> T getBean(String name, Class<T> 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, according to the class .class To get bean
        HRUser user = hrUserDao.findByCode(code);
        if(user != null){
            return user;
        }else{
            return  null;
        }
    }
}

Related articles: