Spring普通类如何引用service或mapper层接口

在传统MVC或者springboot框架中,经常要使用@Autowired注解注入Service或者Mapper接口,在controller层中注入service接口,在service层中注入其它的service接口或者mapper接口都是可以的,但是如果要在自己封装的Utils工具类中或者非controller普通类中使用@Autowired注解注入Service或者Mapper接口,直接注入是不可能的,因为Utils使用了静态的方法,我们是无法直接使用非静态接口的,当遇到这样的问题,就要想办法解决了。
有两种方法解决这个问题,第一种是注解方式,第二种是xml配置方式,下面是在utils中使用@Autowired注解的方法:
第一种主要分为三步:
1, 类方法名标注:@Component
2,使用@Autowired注入service或者mapper层
2, public static 类名 简写;如下的 public static TestUtils testUtils;
3,@PostConstruct注解,参照如下的init()方法
4,直接引用service层或者mapper:类名.service类名.方法名

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

第二种方法就是xml配置的方式,把init()方法上的@PostConstruct注解去掉,在spring-comtext.xml中配置以下bean

<bean id="testUtils" class="这里写utils类的包全路径名" init-method="init"></bean>

非原创:原文链接http://www.tpyyes.com/a/javaweb/30.html根据自己的理解,加了一些总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值