• 解决非controller使用@Autowired注解注入为null问题


    在SpringMVC框架中,我们经常要使用@Autowired注解注入Service或者Mapper接口,我们也知道,在controller层中注入service接口,在service层中注入其它的service接口或者mapper接口都是可以的,但是如果我们要在我们自己封装的Utils工具类中或者非controller普通类中使用@Autowired注解注入Service或者Mapper接口,直接注入是不可能的,因为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();
    }

    如果以上不能解决,只能直接用 dao层:
    ApplicationContext context = new ClassPathXmlApplicationContext('classpath:spring/applicationContext-*.xml');
    FcglEsHouseMapper sfMapper = context.getBean(FcglEsHouseMapper.class);

    然后直接调mybatis接口,不推荐此种,违背springmvc

  • 相关阅读:
    php冒泡排序和快速排序
    在thinkphp中js文件添加路径
    cookiesession
    搭建nginx环境(参考腾讯云实验室)
    验证码快速刷新
    使用Word发送,测试一下
    c++ DLL和c#之间传递字符串
    如何使CEF支持Flash
    如何在Windows上从源码编译Chromium (CEF3) 加入mp3支持
    C#在Linux+Mono环境中使用微信支付证书
  • 原文地址:https://www.cnblogs.com/zhaoyan001/p/10831203.html
Copyright © 2020-2023  润新知