第一步:先检查Spring+SpringMVC配置文件中是否添加了扫描配置
第二步:检查实体类,接口,实现类,dao类是否都已经加上注解
第三步:检查web.xml中是否已经配置好了扫描Spring+SpringMVC的配置文件
还有一种可能发生的问题是Spring Task中的定时任务导致无法注入service
具体解决办法是
添加一个ApplicationContextUtil工具类并且实现ApplicationContextAware 接口
package com.jxufe.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
}
然后按如下方式获取service
private UserService userService = (UserService) ApplicationContextUtil.getBean("userServiceImpl");
最后的话我把我自己的applicationContext.xml、SpringMVC.xml、web.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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<context:component-scan base-package="com.jxufe">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Component" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
<context:component-scan base-package="com">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 加载配数据源配置文件 db.properties -->
<context:property-placeholder location="classpath:config/db.properties" />
<!-- 配置 C3P0 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${datasource.connection.driver_class}"/>
<property name="jdbcUrl" value="${datasource.connection.url}"/>
<property name="user" value="${datasource.connection.username}"/>
<property name="password" value="${datasource.connection.password}"/>
<property name="minPoolSize" value="${datasource.connection.minPoolSize}"/>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="${datasource.connection.maxPoolSize}"/>
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="${datasource.connection.maxIdleTime}"/>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="${datasource.connection.acquireIncrement}"/>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
<property name="maxStatements" value="${datasource.connection.maxStatements}"/>
<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
<property name="maxStatementsPerConnection"
value="${datasource.connection.maxStatementsPerConnection}"/>
<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="${datasource.connection.initialPoolSize}"/>
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod"
value="${datasource.connection.idleConnectionTestPeriod}"/>
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts"
value="${datasource.connection.acquireRetryAttempts}"/>
<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->
<property name="breakAfterAcquireFailure"
value="${datasource.connection.breakAfterAcquireFailure}"/>
<!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
等方法来提升连接测试的性能。Default: false -->
<property name="testConnectionOnCheckout"
value="${datasource.connection.testConnectionOnCheckout}"/>
<property name="checkoutTimeout" value="${datasource.connection.checkoutTimeout}"/>
<property name="testConnectionOnCheckin"
value="${datasource.connection.testConnectionOnCheckin}"/>
<property name="automaticTestTable" value="${datasource.connection.automaticTestTable}"/>
<property name="acquireRetryDelay" value="${datasource.connection.acquireRetryDelay}"/>
<!--自动超时回收Connection-->
<property name="unreturnedConnectionTimeout" value="${datasource.connection.unreturnedConnectionTimeout}"/>
<!--超时自动断开-->
<property name="maxIdleTimeExcessConnections" value="${datasource.connection.maxIdleTimeExcessConnections}"/>
<property name="maxConnectionAge" value="${datasource.connection.maxConnectionAge}"/>
</bean>
<!-- 事务管理器 (JDBC) -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 启动声明式事务驱动 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- spring 通过 sqlSessionFactoryBean 获取 sqlSessionFactory 工厂类 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 扫描 po 包,使用别名 -->
<property name="typeAliasesPackage" value="com.jxufe.entity"></property>
<!-- 扫描映射文件 -->
<property name="mapperLocations" value="classpath:config/mybatis/mapper/*.xml"></property>
</bean>
<!-- 配置扫描 dao 包,动态实现 dao 接口,注入到 spring 容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.jxufe.dao" />
<!-- 注意使用 sqlSessionFactoryBeanName 避免出现spring 扫描组件失效问题 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<bean id="gson" class="com.google.gson.Gson" scope="prototype"></bean>
</beans>
<?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:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<!-- 只需要扫描包中的 Controller 注解 -->
<context:component-scan base-package="com.jxufe.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 启动 mvc 注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 启动定时任务 -->
<task:annotation-driven/>
<!-- 静态资源处理 -->
<mvc:default-servlet-handler/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小限制 -->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!-- 请求的编码格式, 和 jsp 页面一致 -->
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
<!-- 后台访问拦截器 -->
<!-- <mvc:interceptors>-->
<!-- <mvc:interceptor>-->
<!-- <mvc:mapping path="/**"/>-->
<!-- <!–<mvc:mapping path="/grade/*"/>–>-->
<!-- <mvc:exclude-mapping path="/system/login"/>-->
<!-- <mvc:exclude-mapping path="/system/get_cpacha"/>-->
<!-- <mvc:exclude-mapping path="/h-ui/**"/>-->
<!-- <mvc:exclude-mapping path="/easyui/**"/>-->
<!-- <mvc:exclude-mapping path="/home-resources/**"/>-->
<!-- <mvc:exclude-mapping path="/home/**"/>-->
<!-- <bean class="com.jxufe.interceptor.LoginInterceptor"></bean>-->
<!-- </mvc:interceptor>-->
<!-- </mvc:interceptors>-->
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 中文乱码处理 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring配置文件信息 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring/applicationContext.xml</param-value>
</context-param>
<!-- ContextLoaderListener监听器 -->
<!-- ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 日志配置 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:config/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 配置前端控制器 -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/springmvc/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/errors/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/errors/500.jsp</location>
</error-page>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
关于这个问题最后一句话,一定要注意web.xml中的ContextLoaderListener监听器,没有这个,启动web的时候将无法自动加载applicationContext.xml
注意!!!!!!!