Springboot 在普通类型注入Service或mapper

作者:qq_29235677 时间:2023-11-29 15:26:21 

Springboot 在普通类型注入Service或mapper

最近遇到一个难题(大佬可能感觉这太简单了把),对于我这样的小白来说,确实有些头疼。

接下来说一下我遇到的问题,在spring boot中创建了一个UDP客户端,用于监听UDP服务端发送到数据。在实现这一功能时遇到主要遇到了两个难题

1.由于之前都是通过controller调用service层来实现访问

现在要建立一个持久的连接来实现监听某一端口的数据,由于做的项目不多,经验不足,spring也没怎么学过所以困扰了很久。

只是在main方法中开启一个线程简单的new创建实例解决了该问题,虽然不知道这样做对不对,但是能实现功能。(如有更好的办法请告诉小白,谢谢)


@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();  
   }
}

客户端虽然能够启动,但是新的问题又来了

2.在拿到数据之后,掉service时出现空指针

这又困扰了小白两天,通过这篇文章得到了这样的解决方案

(1)首先需要新建一个类,实现 ApplicationContextAware 接口。

要@Conponment注解


  @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;
               }
           }

//获取applicationContext
           public static ApplicationContext getApplicationContext() {
               return applicationContext;
           }

//通过name获取 Bean.
           public static Object getBean(String name){
               return getApplicationContext().getBean(name);
           }

//通过class获取Bean.
           public static <T> T getBean(Class<T> clazz){
               return getApplicationContext().getBean(clazz);
           }

//通过name,以及Clazz返回指定的Bean
           public static <T> T getBean(String name,Class<T> clazz){
               return getApplicationContext().getBean(name, clazz);
           }
       }

(2)在UDP类中获取ApplicationContext对象,然后去获取需要的service 或者 dao。

@Service注解,将自动注册到Spring容器,不需要再在applicationContext.xml文件定义bean了,类似的还包括@Component、@Repository、@Controller。

ApplicationContext又是spring管理bean的容器,加载配置文件的时候,就会将Spring管理的类都实例化。所以就能够注入到该实例。


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.创建数据包
           byte[] buf = new byte[1024];
           DatagramPacket dp = new DatagramPacket(buf, buf.length);

// 3.使用接受方法将数据存储到数据包中
           ds.receive(dp);// 阻塞式的

// 4.通过数据包对象的方法,解析其中的数据 数据内容
       //    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();
   }
}

头疼的问题终于解决了!开心~

springboot 普通类怎么使用注入

需要自定义方法:


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:用于普通类也能使用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;
       }
   }
   /**
    * 拿到ApplicationContext对象实例后就可以手动获取Bean的注入实例对象
    */
   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);
   }
}

使用:


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);//此处根据类.class来获取bean
       HRUser user = hrUserDao.findByCode(code);
       if(user != null){
           return user;
       }else{
           return  null;
       }
   }
}

来源:https://blog.csdn.net/qq_29235677/article/details/88538423

标签:Springboot,普通类,注入,Service,mapper
0
投稿

猜你喜欢

  • AOP之事务管理<aop:advisor>的两种配置方式

    2023-11-24 22:55:06
  • Java中Validated、Valid 、Validator区别详解

    2023-11-11 13:53:31
  • jsp+servlet实现简单登录页面功能(附demo)

    2023-09-24 11:32:28
  • 基于java ssm springboot+mybatis酒庄内部管理系统设计和实现

    2023-09-24 23:51:17
  • java导出数据库的全部表到excel

    2023-11-25 09:38:33
  • JAVA反射机制实例教程

    2023-11-25 23:33:47
  • 通过实例解析Socket套接字通信原理

    2023-11-02 20:17:35
  • 详解java模板和回调机制

    2023-08-13 15:33:46
  • 安卓GreenDao框架一些进阶用法整理

    2023-06-17 03:27:21
  • c语言动态数组示例

    2023-11-02 22:56:44
  • java搭建ftp/sftp进行数据传递的全过程

    2023-11-29 15:08:10
  • 详解Eclipse 字体、字号的设置、最佳字体推荐

    2023-11-26 12:25:32
  • Android Studio和Gradle使用不同位置JDK的问题解决

    2023-06-27 17:35:04
  • Java后台线程操作示例【守护线程】

    2023-11-25 01:35:44
  • Java KindEditor粘贴图片自动上传到服务器功能实现

    2023-08-07 01:42:33
  • jsp如何获取Session中的值

    2023-07-01 05:59:28
  • Android版本更新实例详解

    2023-08-05 21:54:54
  • android自定义环形对比图效果

    2023-06-15 19:49:19
  • Java代码实现酒店管理系统

    2023-08-13 13:09:23
  • SpringBoot项目多数据源及mybatis 驼峰失效的问题解决方法

    2023-07-25 07:09:08
  • asp之家 软件编程 m.aspxhome.com