您好,登錄后才能下訂單哦!
本篇內容主要講解“Springboot怎么在普通類型注入Service或mapper”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Springboot怎么在普通類型注入Service或mapper”吧!
最近遇到一個難題(大佬可能感覺這太簡單了把),對于我這樣的小白來說,確實有些頭疼。
接下來說一下我遇到的問題,在spring boot中創建了一個UDP客戶端,用于監聽UDP服務端發送到數據。在實現這一功能時遇到主要遇到了兩個難題
現在要建立一個持久的連接來實現監聽某一端口的數據,由于做的項目不多,經驗不足,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(); } }
客戶端雖然能夠啟動,但是新的問題又來了
這又困擾了小白兩天,通過這篇文章得到了這樣的解決方案
(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(); } }
頭疼的問題終于解決了!開心~
需要自定義方法:
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; } } }
到此,相信大家對“Springboot怎么在普通類型注入Service或mapper”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。