SSM SpringMVC 非Controller类使用@Autowired注解Service为null的解决办法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34873338/article/details/79309675

在SSM项目开发中,遇到了一个问题,在非Controller类中使用@Autowired注解的Service类一直报NullPointerException,经过一番搜索,由于这个项目情况比较特殊,网上的说的大部分解决方法基本大同小异,并不能解决我的问题,但有了一些解决问题的思路,做一个学习笔记。

解决思路:

1.考虑过在使用Service的类中,直接new一个service对象,但又遇到一个问题就是,如果你Service中使用的Dao也是通过@Autowired注解注入的,那么如果你直接new service同样会抛异常。
总结就是:如果你的Dao是使用@Autowired注入,那么包括调用它的servcie都要进行@Autowired注入,否则之后的注入就会失败。

2.下面是我的解决办法,相信会有更好的办法:

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">


        ...
        ...
        ...

        <!-- 在applicationContext使用配置Service -->
        <bean class="com.wzzc.service.UserService" id="userService"></bean>

</beans>

要用到Service的类

public class GuacamoleTunnelServlet extends GuacamoleHTTPTunnelServlet {

    //注意这里不使用注解
    private UserService userService;

    @Override
    public void init() throws ServletException {
        //通过ApplicationContext加载userService
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        userService=(UserService) applicationContext.getBean("userService");
    }

    ...
    ...
    ...
}

猜你喜欢

转载自blog.csdn.net/qq_34873338/article/details/79309675
今日推荐