Spring boot 中普通类型如何注入Service或mapper

28 篇文章 0 订阅
1 篇文章 0 订阅

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

接下来说一下我遇到的问题,在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时出现空指针。这又困扰了小白两天,通过查博客得到了这样的解决方案

https://blog.csdn.net/yft_android/article/details/79166793

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




    }

}

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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 项目,通常会采用 MVC 架构的设计思路,将代码按照功能分为 Mapper、Entity、Service 和 Controller 四个层次。 1. Mapper Mapper 层是连接数据库和业务逻辑的桥梁,它使用 MyBatis 等 ORM 工具来实现数据库操作。在 Mapper,通常会定义以下内容: - 定义 SQL 语句和参数映射 - 定义查询条件和排序方式 - 定义对数据库的增删改查操作 Mapper 层的示例代码如下: ``` @Mapper public interface UserMapper { @Select("select * from user where id=#{id}") User getUserById(Long id); @Insert("insert into user(name, age) values(#{name}, #{age})") int addUser(User user); @Update("update user set name=#{name}, age=#{age} where id=#{id}") int updateUser(User user); @Delete("delete from user where id=#{id}") int deleteUser(Long id); } ``` 2. Entity Entity 层是与数据库表进行映射的实体。在 Entity 层,通常会定义以下内容: - 定义实体的属性和对应的数据库表字段 - 定义实体之间的关系 Entity 层的示例代码如下: ``` @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // 省略 getter 和 setter 方法 } ``` 3. Service Service 层是业务逻辑的处理层,它主要负责处理业务逻辑和调用 Mapper 层完成数据库操作。在 Service,通常会定义以下内容: - 定义业务逻辑的方法 - 定义事务的管理方法 Service 层的示例代码如下: ``` @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserById(Long id) { return userMapper.getUserById(id); } public int addUser(User user) { return userMapper.addUser(user); } public int updateUser(User user) { return userMapper.updateUser(user); } public int deleteUser(Long id) { return userMapper.deleteUser(id); } } ``` 4. ServiceImpl ServiceImpl 层是 Service 层的实现,它实现了 Service 层定义的业务逻辑方法,并调用 Mapper 层完成数据库操作。在 ServiceImpl 层,通常会定义以下内容: - 实现 Service 层定义的业务逻辑方法 - 定义事务的管理方法 ServiceImpl 层的示例代码如下: ``` @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.getUserById(id); } @Override public int addUser(User user) { return userMapper.addUser(user); } @Override public int updateUser(User user) { return userMapper.updateUser(user); } @Override public int deleteUser(Long id) { return userMapper.deleteUser(id); } } ``` 以上就是 Spring Boot Mapper、Entity、ServiceServiceImpl 四个层次的概述和示例代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智达教育‍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值