您的位置:首页 > 编程语言 > Java开发

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

2018-02-11 11:59 876 查看
在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");
}

...
...
...
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ssm springmvc 注解
相关文章推荐