Springboot 在普通类型注入Service或mapper

目录
  • Springboot 在普通类型注入Service或mapper
    • 1.由于之前都是通过controller调用service层来实现访问
    • 2.在拿到数据之后,掉service时出现空指针
  • springboot 普通类怎么使用注入

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • springboot实现在工具类(util)中调用注入service层方法

    一.新建BeanUtil类 import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.Applic

  • 关于spring boot中几种注入方法的一些个人看法

    前言 最近在知乎上面看到一篇关于程序员面试的问题,面试官问我们一般有几种注入的方法,这几种注入的方法分别在什么时候运用比合理,当时我看到这个时候懵逼了,由于我自己也是刚刚接触springboot不久,所以就自己在平时运用的上面总结了一些知识点常用的几种springboot的注入方法,由于我是一个小萌新,所只要是能够起道注入的方法的注解我都列出来,有可能会有错,希望大家能够及时提出来我来解决: @Autowired @Resource @Component @Configuration @Qual

  • 解决springboot mapper注入报红问题

    目录 springboot mapper注入报红 在mapper接口上加上 @Autowired自动注入时,mapper标红 为什么会标红? 解决方法 springboot mapper注入报红 在mapper接口上加上 @Component注解 例如: 好了,红线没了. @Autowired自动注入时,mapper标红 问题:SpringBoot中,service层使用@Autowired自动注入时,mapper标红 为什么会标红? 我们使用的@Mapper和@MapperScan并不是spr

  • Springboot 在普通类型注入Service或mapper

    目录 Springboot 在普通类型注入Service或mapper 1.由于之前都是通过controller调用service层来实现访问 2.在拿到数据之后,掉service时出现空指针 springboot 普通类怎么使用注入 Springboot 在普通类型注入Service或mapper 最近遇到一个难题(大佬可能感觉这太简单了把),对于我这样的小白来说,确实有些头疼. 接下来说一下我遇到的问题,在spring boot中创建了一个UDP客户端,用于监听UDP服务端发送到数据.在实现

  • java实现在普通类中注入service或mapper

    普通类中注入service或mapper 1.类加@Component注解 2.注入需要引入的service @Autowired private UserService userService; 3.建静态文件 private static UserService users; 4.初始化方法 @PostConstruct public void init() { users= userService; } 5.调用 users.selectUser(user); mapper为null的情况

  • 详解SpringBoot 解决拦截器注入Service为空问题

    一.自定义拦截器实现 HandlerInterceptor 接口 /** * * Created by zhh on 2018/04/20. */ public class MyInterceptor implements HandlerInterceptor { @Autowired private NetworkProxyInfoService networkProxyInfoService; @Override public void afterCompletion(HttpServlet

  • java静态工具类注入service出现NullPointerException异常处理

    目录 一般我们在controller层调用service时,只需要使用@Autowired注解即可,例如如下代码我们经常看到: @RestController @RequestMapping("business") public class BizResourceController { @Autowired private BusinessService businessService; @RequestMapping(path = "/queryYearList"

  • SpringBoot中的main方法注入service

    一.SpringBoot中的main方法注入service 在springboot中使用main方法常规无法注入service,因为以后也可能会有这种情况,所以采取工具类的方式进行,该工具类为固定写法,直接复制就行 @Component public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @O

  • 详解关于mybatis-plus中Service和Mapper的分析

    在后端开发过程中,如果有用到mybatis-plus,肯定会发现在其内部存在着两种数据库操作接口,Iservice和BaseMapper,如果只是用增删改查会发现两者的功能是一致的,除了方法名称有所不同,其他的基本相似.对此,我颇为好奇,便打开两个接口的源码进行对比. 先演示一下基本开发中的继承关系,手动创建的Service继承于ServiceImpl,并加载自己创建的Mapper @Service public class RestDeptService extends ServiceImpl

  • 如何在Netty中注解使用Service或者Mapper

    目录 Netty注解使用Service或Mapper Handler Server 创建Server 二次修订 Netty handler注入service为空 注入方式 Netty注解使用Service或Mapper SpringBoot搭配Netty使用,在Handler中注解使用Service/Mapper 一直 为null.起初使用 SpringBoot启动类继承ApplicationContextAware,再写一个静态方法获取Bean来解决. 放在服务器上跑了几个小时就出现了问题,好

  • SpringBoot整合MyBatis逆向工程及 MyBatis通用Mapper实例详解

    一.添加所需依赖,当前完整的pom文件如下: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&q

  • SpringBoot如何防止XSS注入攻击详解

    什么是 XSS 攻击 在跨站脚本(XSS)攻击中,攻击者可以在受害者的浏览器中执行恶意脚本.这种攻击通常是通过在网页中插入恶意代码 (JavaScript) 来完成的.攻击者在使用攻击后一般能够: 修改网页内容 将用户重定向到其他网站 访问用户的 Cookie 并利用此信息来冒充用户 访问有关用户系统的关键信息,例如地理位置,网络摄像头,文件系统 将木马功能注入应用程序 如果被攻击的用户在应用程序中具有更高的权限.攻击者可以完全控制应用程序,并破坏所有用户及其数据. XSS 攻击类型 常见的 X

  • springboot 如何解决static调用service为null

    springboot static调用service为null @PostConstruct注解好多人以为是Spring提供的.其实是Java自己的注解. Java中该注解的说明: @PostConstruct该注解被用来修饰一个非静态的void()方法.被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次.PostConstruct在构造函数之后执行,init()方法之前执行. 通常我们会是在Spring框架中使用到@PostConstruc

随机推荐