javaweb各种框架组合案例(四):maven+spring+springMVC+spring data jpa【失败案例】
程序员文章站
2022-03-20 21:17:40
一、失败案例 1. 控制台报错信息 2. 初步判断 spring data jpa 无法自动实现dao层接口 3. 原因 未知,非扫描包问题 二、项目 1. 项目整体包结构 2. 业务 实现一个用户具有多部手机的业务 3. 各配置文件 (1)pom.xml (2)spring-context.xml ......
一、失败案例
1. 控制台报错信息
严重: exception sending context initialized event to listener instance of class org.springframework.web.context.contextloaderlistener org.springframework.beans.factory.unsatisfieddependencyexception: error creating bean with name 'userserviceimpl': unsatisfied dependency expressed through field 'userdao'; nested exception is org.springframework.beans.factory.beancreationexception: error creating bean with name 'userdao': invocation of init method failed; nested exception is java.util.nosuchelementexception at org.springframework.beans.factory.annotation.autowiredannotationbeanpostprocessor$autowiredfieldelement.inject(autowiredannotationbeanpostprocessor.java:588) at org.springframework.beans.factory.annotation.injectionmetadata.inject(injectionmetadata.java:88) at org.springframework.beans.factory.annotation.autowiredannotationbeanpostprocessor.postprocesspropertyvalues(autowiredannotationbeanpostprocessor.java:366) at org.springframework.beans.factory.support.abstractautowirecapablebeanfactory.populatebean(abstractautowirecapablebeanfactory.java:1264) at org.springframework.beans.factory.support.abstractautowirecapablebeanfactory.docreatebean(abstractautowirecapablebeanfactory.java:553) at org.springframework.beans.factory.support.abstractautowirecapablebeanfactory.createbean(abstractautowirecapablebeanfactory.java:483) at org.springframework.beans.factory.support.abstractbeanfactory$1.getobject(abstractbeanfactory.java:306) at org.springframework.beans.factory.support.defaultsingletonbeanregistry.getsingleton(defaultsingletonbeanregistry.java:230) at org.springframework.beans.factory.support.abstractbeanfactory.dogetbean(abstractbeanfactory.java:302) at org.springframework.beans.factory.support.abstractbeanfactory.getbean(abstractbeanfactory.java:197) at org.springframework.beans.factory.support.defaultlistablebeanfactory.preinstantiatesingletons(defaultlistablebeanfactory.java:761) at org.springframework.context.support.abstractapplicationcontext.finishbeanfactoryinitialization(abstractapplicationcontext.java:867) at org.springframework.context.support.abstractapplicationcontext.refresh(abstractapplicationcontext.java:543) at org.springframework.web.context.contextloader.configureandrefreshwebapplicationcontext(contextloader.java:443) at org.springframework.web.context.contextloader.initwebapplicationcontext(contextloader.java:325) at org.springframework.web.context.contextloaderlistener.contextinitialized(contextloaderlistener.java:107) at org.apache.catalina.core.standardcontext.listenerstart(standardcontext.java:4797) at org.apache.catalina.core.standardcontext.startinternal(standardcontext.java:5291) at org.apache.catalina.util.lifecyclebase.start(lifecyclebase.java:150) at org.apache.catalina.core.containerbase$startchild.call(containerbase.java:1559) at org.apache.catalina.core.containerbase$startchild.call(containerbase.java:1549) at java.util.concurrent.futuretask.run(futuretask.java:266) at java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1149) at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:624) at java.lang.thread.run(thread.java:748)
2. 初步判断
spring data jpa 无法自动实现dao层接口
3. 原因
未知,非扫描包问题
二、项目
1. 项目整体包结构
2. 业务
实现一个用户具有多部手机的业务
3. 各配置文件
(1)pom.xml
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.xiaog</groupid> <artifactid>testssdj</artifactid> <version>0.0.1-snapshot</version> <packaging>war</packaging> <dependencies> <!-- spring+springmvc*依赖包,包含spring-webmvc、spring-aop、spring-beans、 spring-context、spring-core、spring-jcl、spring-expression、spring-web --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-webmvc</artifactid> <version>4.3.10.release</version> </dependency> <!-- spring-aop所依赖的静态代理 , 使用aop方式管理事务,在service方法执行前开启事务, 方法执行后提交事务,方法执行失败回滚事务--> <dependency> <groupid>org.aspectj</groupid> <artifactid>aspectjrt</artifactid> <version>1.8.0</version> </dependency> <dependency> <groupid>org.aspectj</groupid> <artifactid>aspectjweaver</artifactid> <version>1.8.0</version> </dependency> <!-- 数据库方面 --> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.47</version> </dependency> <dependency> <groupid>com.alibaba</groupid> <artifactid>druid</artifactid> <version>1.1.10</version> </dependency> <!-- orm框架 --> <dependency> <groupid>org.hibernate</groupid> <artifactid>hibernate-core</artifactid> <version>4.2.2.final</version> </dependency> <dependency> <groupid>org.hibernate</groupid> <artifactid>hibernate-entitymanager</artifactid> <version>4.2.2.final</version> </dependency> <!-- spring data jpa --> <dependency> <groupid>org.springframework.data</groupid> <artifactid>spring-data-jpa</artifactid> <version>1.11.3.release</version> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-api</artifactid> <version>1.7.25</version> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-log4j12</artifactid> <version>1.7.25</version> </dependency> <!-- logback --> <!-- <dependency> <groupid>ch.qos.logback</groupid> <artifactid>logback-classic</artifactid> <version>0.9.19</version> </dependency> <dependency> <groupid>org.logback-extensions</groupid> <artifactid>logback-ext-spring</artifactid> <version>0.1.2</version> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>jcl-over-slf4j</artifactid> <version>1.6.6</version> </dependency> --> <!-- jsp需要 --> <dependency> <groupid>javax.servlet</groupid> <artifactid>servlet-api</artifactid> <version>3.0-alpha-1</version> <scope>provided</scope> </dependency> <dependency> <groupid>jstl</groupid> <artifactid>jstl</artifactid> <version>1.1.2</version> </dependency> </dependencies> <build> <defaultgoal>compile</defaultgoal> <plugins> <!-- maven插件 --> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-compiler-plugin</artifactid> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>utf-8</encoding> </configuration> </plugin> <!-- tomcat插件 --> <plugin> <groupid>org.apache.tomcat.maven</groupid> <artifactid>tomcat7-maven-plugin</artifactid> <version>2.1</version> <configuration> <port>9999</port> <path>/testssdj</path> <uriencoding>utf-8</uriencoding> <finalname>testssdj</finalname> <server>tomcat7</server> </configuration> </plugin> </plugins> </build> </project>
(2)spring-context.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> <!--指定连接池配置 --> <!-- dao层 数据库连接部分 --> <!-- 加载配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置service扫描 --> <context:component-scan base-package="com.xiaog.service" /> <!-- 数据库连接池 --> <bean id="datasource" class="com.alibaba.druid.pool.druiddatasource" destroy-method="close"> <property name="driverclassname" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 连接池的最大数据库连接数 --> <property name="maxactive" value="10" /> <!-- 最大空闲数 --> <property name="maxidle" value="5" /> </bean> <!-- spring整合jpa --> <bean id="entitymanagerfactory" class="org.springframework.orm.jpa.localcontainerentitymanagerfactorybean"> <property name="datasource" ref="datasource"/> <property name="jpavendoradapter"> <bean class="org.springframework.orm.jpa.vendor.hibernatejpavendoradapter"></bean> </property> <!-- 配置包扫描,扫描实体 --> <property name="packagestoscan" value="com.xiaog.entity"/> <property name="jpaproperties"> <props> <!-- 生成的数据表的列的映射策略 --> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.improvednamingstrategy</prop> <!-- hibernate 基本属性 --> <prop key="hibernate.dialect">org.hibernate.dialect.mysql5innodbdialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- 配置事务管理器 --> <bean id="transactionmanager" class="org.springframework.orm.jpa.jpatransactionmanager"> <property name="entitymanagerfactory" ref="entitymanagerfactory" /> </bean> <!-- 开启事务注解 --> <tx:annotation-driven transaction-manager="transactionmanager" /> <!--指定spring data jpa要进行扫描的包,该包中的类框架会自动为其创建代理 --> <jpa:repositories base-package="com.xiaog.dao" entity-manager-factory-ref="entitymanagerfactory"></jpa:repositories> </beans>
(3)spring-mvc.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-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!--配置controller扫描--> <context:component-scan base-package="com.xiaog.controller"/> <!-- 注解驱动 --> <mvc:annotation-driven/> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
(4)jdbc.properties
jdbc.driver=com.mysql.jdbc.driver jdbc.url=jdbc:mysql://localhost:3306/ssdj?usessl=false&useunicode=true&characterencoding=utf8 jdbc.username=root jdbc.password=root
(5)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" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>testssdj</display-name> <!-- spring配置文件路径 --> <context-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:spring-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!-- 解决post乱码问题 --> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class> <!-- 设置编码参是utf8 --> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置springmvc 前端控制器 --> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <!--指定springmvc 配置文件 --> <init-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 添加日志监听器 --> <!-- <context-param> <param-name>logbackconfiglocation</param-name> <param-value>classpath:logback.xml</param-value> </context-param> <listener> <listener-class>ch.qos.logback.ext.spring.web.logbackconfiglistener</listener-class> </listener> --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
4. 实体层
package com.xiaog.entity; import javax.persistence.entity; import javax.persistence.generatedvalue; import javax.persistence.generationtype; import javax.persistence.id; import javax.persistence.table; @entity @table(name="phone") public class phone { @id @generatedvalue(strategy=generationtype.identity) private integer id; private string brand;//品牌 public integer getid() { return id; } public void setid(integer id) { this.id = id; } public string getbrand() { return brand; } public void setbrand(string brand) { this.brand = brand; } @override public string tostring() { return "phone [id=" + id + ", brand=" + brand + "]"; } }
package com.xiaog.entity; import java.util.list; import javax.persistence.entity; import javax.persistence.generatedvalue; import javax.persistence.generationtype; import javax.persistence.id; import javax.persistence.joincolumn; import javax.persistence.onetomany; import javax.persistence.table; @entity @table(name="user") public class user { @id @generatedvalue(strategy=generationtype.identity) private integer id; private string username; private string password; @onetomany(targetentity=phone.class) @joincolumn(name="user_id") private list<phone> phones;//一个用户拥有多部手机 public integer getid() { return id; } public void setid(integer id) { this.id = id; } public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } public list<phone> getphones() { return phones; } public void setphones(list<phone> phones) { this.phones = phones; } @override public string tostring() { return "user [id=" + id + ", username=" + username + ", password=" + password + ", phones=" + phones + "]"; } }
5. dao层
package com.xiaog.dao; import org.springframework.data.jpa.repository.jparepository; import org.springframework.stereotype.repository; import com.xiaog.entity.phone; @repository public interface phonedao extends jparepository<phone, integer> { }
package com.xiaog.dao; import org.springframework.data.jpa.repository.jparepository; import org.springframework.stereotype.repository; import com.xiaog.entity.user; @repository public interface userdao extends jparepository<user, integer> { user findbyusernameandpassword(user user); }
6. service层
package com.xiaog.service; import com.xiaog.entity.user; public interface userservice { user login(user user); }
package com.xiaog.service.impl; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import org.springframework.transaction.annotation.transactional; import com.xiaog.dao.userdao; import com.xiaog.entity.user; import com.xiaog.service.userservice; @service @transactional public class userserviceimpl implements userservice { @autowired private userdao userdao; private final static logger logger = loggerfactory.getlogger(userserviceimpl.class); @override public user login(user user) { //logger.info("进入userserviceimpl......"); user = userdao.findbyusernameandpassword(user); logger.info("user="+user); return user; } }
7.controller层
package com.xiaog.controller; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.controller; import org.springframework.ui.model; import org.springframework.web.bind.annotation.requestmapping; import com.xiaog.entity.user; import com.xiaog.service.userservice; @controller @requestmapping("/user") public class usercontroller { @autowired(required=false) private userservice userservice; private final static logger logger = loggerfactory.getlogger(usercontroller.class); @requestmapping(value = "/login",params= {"username","password","username!=","password!="}) public string login(model model,user user) { logger.info("user(request)="+user); user = userservice.login(user); logger.info("user="+user); model.addattribute("user", user); return "result"; } }
8.jsp页面
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html> <html> <head> <meta charset="utf-8"> <title>insert title here</title> </head> <body> <form action="user/login" method="post"> <div> <label>username</label> <input type="text" name="username"/> </div> <div> <label>password</label> <input type="password" name="password"/> </div> <div> <input type="submit" value="登录"> </div> </form> </body> </html>
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> username=${user} </body> </html>
三、求解决
若有大神能够解决问题,在下感激不尽