普通类、工具类调用Service接口

一、背景

在SpringMVC框架中,我们经常要使用@Autowired注解注入Service或者Mapper接口,我们也知道,在controller层中注入service接口,在service层中注入其它的service接口或者mapper接口都是可以的,但是如果我们要在我们自己封装的Utils工具类中或者非controller普通类中使用@Autowired注解注入Service或者Mapper接口,直接注入是不可能的,因为Utils使用了静态的方法,我们是无法直接使用非静态接口的,当我们遇到这样的问题,我们就要想办法解决了。

二、解决办法(两种办法)

  1. 注解方式
    下面是我们在utils中使用@Autowired注解的方法:
 @Component 
       public class TestUtils {
           @Autowired
           private ItemService itemService;
           
           @Autowired
           private ItemMapper itemMapper;
           
           public static TestUtils testUtils;
           
           @PostConstruct
           public void init() {    
               testUtils = this;
           } 
           
           //utils工具类中使用service和mapper接口的方法例子,用"testUtils.xxx.方法" 就可以了      
           public static void test(Item record){
               testUtils.itemMapper.insert(record);
               testUtils.itemService.queryAll();
           }
       }

@PostConstruct注解好多人以为是Spring提供的,其实是Java自己的注解。
Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
2. xml配置方式
我们可以把init()方法上的@PostConstruct注解去掉,在spring-comtext.xml中配置以下bean就好了,里面什么内容都不用写,是不是很简单?

三、参考网站
本文档参考网址
SpringBoot Controller单元测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值