本篇内容主要讲解“Springboot怎么在普通类型注入Service或mapper”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Springboot怎么在普通类型注入Service或mapper”吧!
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;@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; } } 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; } }}
到此,相信大家对“Springboot怎么在普通类型注入Service或mapper”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!