Springboot 在普通類型注入Service或mapper
Springboot 在普通類型注入Service或mapper
最近遇到一個(gè)難題(大佬可能感覺這太簡單了把),對于我這樣的小白來說,確實(shí)有些頭疼。
接下來說一下我遇到的問題,在spring boot中創(chuàng)建了一個(gè)UDP客戶端,用于監(jiān)聽UDP服務(wù)端發(fā)送到數(shù)據(jù)。在實(shí)現(xiàn)這一功能時(shí)遇到主要遇到了兩個(gè)難題
1.由于之前都是通過controller調(diào)用service層來實(shí)現(xiàn)訪問
現(xiàn)在要建立一個(gè)持久的連接來實(shí)現(xiàn)監(jiān)聽某一端口的數(shù)據(jù),由于做的項(xiàng)目不多,經(jīng)驗(yàn)不足,spring也沒怎么學(xué)過所以困擾了很久。
只是在main方法中開啟一個(gè)線程簡單的new創(chuàng)建實(shí)例解決了該問題,雖然不知道這樣做對不對,但是能實(shí)現(xiàn)功能。(如有更好的辦法請告訴小白,謝謝)
@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(); } }
客戶端雖然能夠啟動(dòng),但是新的問題又來了
2.在拿到數(shù)據(jù)之后,掉service時(shí)出現(xiàn)空指針
這又困擾了小白兩天,通過這篇文章得到了這樣的解決方案
(1)首先需要新建一個(gè)類,實(shí)現(xiàn) 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注解,將自動(dòng)注冊到Spring容器,不需要再在applicationContext.xml文件定義bean了,類似的還包括@Component、@Repository、@Controller。
ApplicationContext又是spring管理bean的容器,加載配置文件的時(shí)候,就會將Spring管理的類都實(shí)例化。所以就能夠注入到該實(shí)例。
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.創(chuàng)建數(shù)據(jù)包 byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); // 3.使用接受方法將數(shù)據(jù)存儲到數(shù)據(jù)包中 ds.receive(dp);// 阻塞式的 // 4.通過數(shù)據(jù)包對象的方法,解析其中的數(shù)據(jù) 數(shù)據(jù)內(nèi)容 // 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對象實(shí)例后就可以手動(dòng)獲取Bean的注入實(shí)例對象 */ 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);//此處根據(jù)類.class來獲取bean HRUser user = hrUserDao.findByCode(code); if(user != null){ return user; }else{ return null; } } }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java集合模擬實(shí)現(xiàn)斗地主洗牌和發(fā)牌
這篇文章主要為大家詳細(xì)介紹了java集合模擬實(shí)現(xiàn)斗地主洗牌和發(fā)牌,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09Java實(shí)戰(zhàn)之實(shí)現(xiàn)物流配送系統(tǒng)示例詳解
這篇文章主要介紹了一個(gè)java實(shí)戰(zhàn)項(xiàng)目:通過java、SSM、JSP、mysql和redis實(shí)現(xiàn)一個(gè)物流配送系統(tǒng)。文中的示例代碼非常詳細(xì),需要的朋友可以參考一下2021-12-12Mybatisplus創(chuàng)建Spring?Boot工程打包錯(cuò)誤的解決方式
最近在實(shí)戰(zhàn)springboot遇到了一些坑,記錄一下,下面這篇文章主要給大家介紹了關(guān)于Mybatisplus創(chuàng)建Spring?Boot工程打包錯(cuò)誤的解決方式,文中通過圖文介紹的介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03Java使用Ajax實(shí)現(xiàn)跨域上傳圖片功能
這篇文章主要介紹了Java使用Ajax實(shí)現(xiàn)跨域上傳圖片功能,需要的朋友可以參考下2017-09-09Java讀文件修改默認(rèn)換行符的實(shí)現(xiàn)
這篇文章主要介紹了Java讀文件修改默認(rèn)換行符的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Java字節(jié)碼操縱框架ASM圖文實(shí)例詳解
這篇文章主要為大家介紹了Java字節(jié)碼操縱框架ASM圖文實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07