最近在学基于注解的spring mvc,也是跟着孔浩的视频学得,用的三层结构 controller service 还有DAO,但是运行后发现service没有注入,导致项目的功能运行不正常,调了半天还是没有结果,想请各位高手给解决一下,万分感谢。
代码如下:
Controller
代码如下:
Controller
package com.zrb.controller; import java.util.HashMap; import java.util.Map; import com.zrb.entiy.TBrand; import com.zrb.ucts.service.TBrandService; @Controller @RequestMapping("/brand") public class BrandController { private Map<String,TBrand> tBrands = new HashMap<String, TBrand>(); @Value("#{configProperties["url"]}") private String dbUrl; public BrandController() { tBrands.put("3", new TBrand(3,"马自达")); tBrands.put("4", new TBrand(4,"雪佛兰")); } @Resource(name="brandservice") private TBrandService brandService;
Service 接口
package com.zrb.ucts.service; import java.util.List; import org.springframework.stereotype.Service; import com.zrb.ucts.db.entity.TBrand; @Service("brandservice") public interface TBrandService { // 通过Id查询UserInfo TBrand getById(Integer id); // 查询全部的UserInfo List<TBrand> findAll(); // 添加UserInfo Integer save(TBrand tBrand); }
Service 实现代码
package com.zrb.ucts.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.zrb.ucts.db.dao.TBrandDao; import com.zrb.ucts.db.entity.TBrand; import com.zrb.ucts.service.TBrandService; @Service("brandservice") public class TBrandServiceImpl implements TBrandService { @Resource(name="branddao") private TBrandDao tBrandDao; @Override public TBrand getById(Integer id) { return tBrandDao.getById(id); } @Override public List<TBrand> findAll() { return tBrandDao.findAll(); } @Override public Integer save(TBrand tBrand) { return tBrandDao.save(tBrand); } }
基类DAO
package com.zrb.ucts.db.dao; import com.zrb.ucts.db.entity.TBrand; public interface TBrandDao extends GenericDao<TBrand, Integer>{ }
接口DAO
package com.zrb.ucts.db.dao; import java.io.Serializable; import java.util.List; interface GenericDao<T, PK extends Serializable> { T getById(PK id); List<T> findAll(); PK save(T entity); }
实现DAO
package com.zrb.ucts.db.dao.impl; import java.util.List; import com.zrb.ucts.db.dao.TBrandDao; import com.zrb.ucts.db.entity.TBrand; @Repository("branddao") public class TBrandDaoImpl implements TBrandDao { @Autowired private JdbcTemplate jdbcTemplate; @Autowired private NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Override public TBrand getById(Integer id) { String sql = "SELECT * FROM t_brand WHERE brand_id = ?"; TBrand tBrand = jdbcTemplate.queryForObject(sql, new TBrand(), new Object[] { id }); return tBrand; } @Override public List<TBrand> findAll() { String sql = "SELECT * FROM t_brand"; List<TBrand> tBrands = jdbcTemplate.query(sql, new TBrand()); return tBrands; } @Override public Integer save(TBrand entity) { String sql = "INSERT INTO t_brand(brand_id, brand_name) VALUES(:brandid, :brandname)"; MapSqlParameterSource paramSource = new MapSqlParameterSource(); paramSource.addValue("brandid", entity.getBrandId()); paramSource.addValue("brandname", entity.getBrandName()); int result = namedParameterJdbcTemplate.update(sql, paramSource); return result; } }
web.xml如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>front</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>front</servlet-name> <url-pattern>/front/*</url-pattern> </servlet-mapping> <!-- --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
Spring mvc配置
<?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" xsi:schemaLocation="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.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <mvc:annotation-driven> </mvc:annotation-driven> <context:component-scan base-package="com.zrb.controller"></context:component-scan> <bean name="/welcome.html" class="com.zrb.controller.WelcomeController"></bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
Spring 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" xsi:schemaLocation="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.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/> <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> <!--引入配置属性文件 --> <context:property-placeholder location="classpath*:config/applicationConfig.properties" /> <context:property-placeholder location="classpath*:config/log4j.properties" /> <!--扫描org.andy.work下文件,自动注入dao,entity,service为bean --> <context:component-scan base-package="com.zrb.ucts.db.dao.impl,com.zrb.ucts.service.impl" /> <!-- c3p0数据源配置 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 请求超时时间 --> <property name="checkoutTimeout" value="30000" /> <!-- 每60秒检查全部连接池中的空闲连接。默认值: 0,不检查 --> <property name="idleConnectionTestPeriod" value="30" /> <!-- 连接数据库连接池最大空闲时间 --> <property name="maxIdleTime" value="30" /> <!-- 连接池初始化连接数 --> <property name="initialPoolSize" value="5" /> <property name="minPoolSize" value="5" /> <property name="maxPoolSize" value="20" /> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 --> <property name="acquireIncrement" value="5" /> </bean> <!-- spring jdbc --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource" /> </bean> <!-- 配置事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 声明式事务,事务拦截器 --> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager" ref="transactionManager" /> <!-- 配置事务属性 --> <property name="transactionAttributes"> <!--下面定义事务传播属性 --> <props> <prop key="save*">PROPAGATION_REQUIRED</prop> <prop key="del*">PROPAGATION_REQUIRED</prop> <prop key="update">PROPAGATION_REQUIRED</prop> <prop key="get*">PROPAGATION_SUPPORTS,readOnly</prop> <prop key="find*">PROPAGATION_SUPPORTS,readOnly</prop> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> </beans>
访问后无法注入的异常信息如下:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name "brandController": Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named "brandservice" is defined
解决方案
10
用 @Autowired,又用 @Resource 来注入,好乱,最好只用一种。
10
你的service标志接口和实现类用了同一个Id?好像只要在实现类标志service就行了吧,接口不用
50
<!–扫描org.andy.work下文件,自动注入dao,entity,service为bean –>
<context:component-scan base-package=”com.zrb.ucts.db.dao.impl,com.zrb.ucts.service.impl” />
这里没有扫描到brandController
<context:component-scan base-package=”com.zrb.ucts.db.dao.impl,com.zrb.ucts.service.impl” />
这里没有扫描到brandController
30
本人去检查了下spring mvc配置,需要扫描到controller的
<context:component-scan base-package="com.sishuok.es.**.web.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan>