zoukankan      html  css  js  c++  java
  • 解决非controller使用@Autowired注解注入为null问题

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

    我们有两种方法解决这个问题,第一种是注解方式,第二种是xml配置方式,下面是我们在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();
        }
    }

    我们在init方法中使用以下注解就可以了,时间上这个init()的方法是可以自己随便定义的,注意:inti()方法里面不用写任何东西,跟我这样的就绝对ok了,不用看网上其他人瞎掰!

    @PostConstruct

    第二种方法就是xml配置的方式,也是很简单的,我们可以把init()方法上的@PostConstruct注解去掉,在spring-comtext.xml中配置以下bean就好了,里面什么内容都不用写,是不是很简单?

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

    网上的其它资料都是扯淡,用我这两种方式就绝对ok了。

    来源网站:太平洋学习网,转载请注明出处:http://www.tpyyes.com/a/javaweb/2016/1124/30.html

  • 相关阅读:
    在阿里云“专有网络”网络类型中配置vsftpd
    Ubuntu 16.04下开启Mysql 3306端口远程访问
    .net core 2.0 报错:error NU1102: Unable to find package ...
    .NET Core Runtime ARM32 builds now available
    .NET Core on Raspberry Pi
    .NET Core 跨平台发布(dotnet publish)
    使用vscode开发调试.net core应用程序并部署到Linux跨平台
    docker容器镜像删除
    使用阿里docker镜像加速器加速
    树莓派3b基于UbuntuMate下载中文输入法
  • 原文地址:https://www.cnblogs.com/zhuyf0506/p/7873209.html
Copyright © 2011-2022 走看看