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

2022-06-24 14:27:59

在传统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根据自己的理解,加了一些总结

  • 作者:只会debug
  • 原文链接:https://blog.csdn.net/java_xdo/article/details/105117231
    更新时间:2022-06-24 14:27:59