spring创建sessionFactory错误

严重: Context initialization failed
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'userDao' defined in file [D:\Tomcat8\webapps\log\WEB-INF\classes\com\fjnu\log\config\applicationContext-beans.xml]:
Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in file [D:\Tomcat8\webapps\log\WEB-INF\classes\com\fjnu\log\config\applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: could not instantiate id generator [entity-name=com.fjnu.log.domain.Log]

beans配置
















1个回答

配置文件问题,看看配置bean id = sessionFactory的地方是否正确。 could not instantiate id generator [entity-name=com.fjnu.log.domain.Log]看一下这个配置文件中id主键生成器是否正确,数据库配置以及mapper文件配置

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
spring整合hibernate的sessionFactory,报以下错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerServiceImpl' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'customerDaoImpl' of bean class [cn.itcast.ssh.service.impl.CustomerServiceImpl]: Bean property 'customerDaoImpl' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1518) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) 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:772) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at cn.itcast.ssh.spring_sessionFactory.Spring_SessionFactory.test(Spring_SessionFactory.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:69) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.junit.runners.ParentRunner.run(ParentRunner.java:292) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'customerDaoImpl' of bean class [cn.itcast.ssh.service.impl.CustomerServiceImpl]: Bean property 'customerDaoImpl' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:231) at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:423) at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:280) at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:95) at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1514) ... 36 more **spring的配置文件如下**: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 1.配置查询所有客户的bean对象,注入spring管理的sessionFactory对象 --> <bean id="customerDaoImpl" class="cn.itcast.ssh.dao.impl.CustomerDaoImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="customerServiceImpl" class="cn.itcast.ssh.service.impl.CustomerServiceImpl"> <property name="customerDaoImpl" ref="customerDaoImpl"></property> </bean> <!-- 2.spring管理action的创建和service层注入 --> <bean id="findAllCustomer" class="cn.itcast.ssh.web.action.CustomerAction" scope="prototype"> <property name="customerServiceImpl" ref="customerServiceImpl"></property> </bean> <!-- 3.在spring配置sessionFactory,注入到dao中 ,就是在LocalSessionFactoryBean类中注入一个属性configLocation,其值value就是引用hibernate的sessionFactory--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> </bean> ** 测试类代码如下** package cn.itcast.ssh.spring_sessionFactory; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.ssh.domain.Customer; import cn.itcast.ssh.service.CustomerService; import cn.itcast.ssh.service.impl.CustomerServiceImpl; /** * * @author Hongqiankun 测试spring管理sessionFactory的创建,是否能用 1.手动加载spring的配置文件 * 2.获取serviceImpl的bean对象,调用save方法,由于save中使用了sessionFactory * 所以,如果spring没能成功注入sessionFactory,则程序保存,无法将新的客户信息录入到数据库; * */ public class Spring_SessionFactory { @Test public void test() { //1.加载spring的配置文件,获得CustomerServiceImpl对象 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); CustomerService customerServiceImpl = (CustomerServiceImpl) context.getBean("customerServiceImpl"); //2.创建新的customer Customer cus = new Customer(); cus.setCustName("北方科技2"); cus.setCustAddress("北京"); cus.setCustIndustry("科技公司"); cus.setCustPhone("13214132344"); cus.setCustSource("推广"); cus.setCustLevel("普通客户"); //3.调用saveCustomer方法 customerServiceImpl.saveCustomer(cus); } } </beans>
spring整合hibernate出现sessionFactory的bean创建异常错误
![图片说明](https://img-ask.csdn.net/upload/201602/28/1456643080_131432.png) org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) 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:753) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at com.guigu.ssh.hibernate.test.SpringHibernateTest.<init>(SpringHibernateTest.java:13) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:408) at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:195) at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:244) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:241) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:185) at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:400) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928) at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:372) at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:454) at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:439) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ... 34 more Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer] at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:138) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:188) at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:403) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:520) at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:148) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:408) at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163) ... 43 more Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:408) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:135) ... 52 more Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for userName in class com.guigu.ssh.hibernate.entities.Account at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:310) at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:304) at org.hibernate.mapping.Property.getGetter(Property.java:323) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:411) at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:200) at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:80) ... 57 more 不知道是不是jar包有没有问题 ![图片说明](https://img-ask.csdn.net/upload/201602/28/1456643323_531830.png)
springboot项目创建entityManagerFactory时出错:Error activating Bean Validation integration,如何解决?
在svn上拉下项目来本地时无法开启项目,包和配置都和别人一样,但是别人能启动,项目是springboot2.1.9+JPA+mybatis-plus+mysql+oracle+application.properties 所有配置都写到了application.propertiese中 麻烦熟悉JPA的entityManagerFactory生命周期的大神们帮忙解决下,感激不 尽。 鄙人已尝试过的操作: * 1检查实体类与数据库的字段是否匹配,换springboot的版本。 * 2 重新倒jar包、挂上@Entity @ID @GeneratedValue 、重写get set方法、import javax.persistence.Id。 * 3倒入各种hibernate相关的包和javassist包,换mave版本,重新开maven库单独下载包 具体错误如下 ``` org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.cfg.beanvalidation.IntegrationException: Error activating Bean Validation integration at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.10.RELEASE.jar:5.1.10.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) [spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) [spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) [spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) [spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE] at com.south.robot.RobotApplication.main(RobotApplication.java:13) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.9.RELEASE.jar:2.1.9.RELEASE] ```
springmvc sessionFactory is null
严重: Servlet.service() for servlet [spring2] in context with path [/Lbl] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException 说明:@resource和@annotional都不起作用。 网上的方法都试过了,不起作用 spring2-servlet.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.lbl.active" /> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <bean id="bookXmlView" class="org.springframework.web.servlet.view.xml.MarshallingView"> <constructor-arg> <bean class="org.springframework.oxm.xstream.XStreamMarshaller"> <property name="autodetectAnnotations" value="true"/> </bean> </constructor-arg> </bean> <bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"> </bean> </beans> application.xml <context:annotation-config/> <!-- 自动扫描与装配 --> <context:component-scan base-package="com.lbl"></context:component-scan> <!-- 导入外部的properties--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 配置数据库路径 classpath:WEB-INF\classes\hibernate.cfg.xml--> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 配置数据库c3p0连接池 dataSource写错导致bean创建异常错误信息属性值设置错误 --> <property name="dataSource" > <!-- dataSouce应该写成dataSource第三个错误 --> <bean class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置数据库信息 --> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="driverClass" value="${driverClass}"></property> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> <!-- 其他配置 --> </bean> </property> </bean> <!-- 配置声明事物管理 采用注解方式--> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" > <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="txManager"/> </beans> 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>Lbl</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/applicationContext.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <filter> <filter-name>openSession</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSession</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>spring2</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring2</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> 出错的类 @Transactional public class DaoService<T> implements DaoLbl<T>{ @Resource private SessionFactory sessionFactory; private Class<T> clazz; @SuppressWarnings("unchecked") public DaoService(){ System.out.println("---1---->>>:"+this.getClass()); // System.out.println("----2--->>>:"+this.getClass().getGenericSuperclass()); //使用反射技术获得 T的真实类型 ParameterizedType pt=(ParameterizedType)this.getClass()// .getGenericSuperclass();//获取当前new的泛型父类类型 System.out.println("------->:"); this.clazz=(Class<T>)pt.getActualTypeArguments()[0]; //获取第一个参数的实际类型 System.out.println("class--->" + clazz); } protected Session getSession(){ // // String path="C:/Users/admin/workspace/Lbl/WebContent/WEB-INF/applicationContext.xml"; // ApplicationContext ac=new FileSystemXmlApplicationContext(path); // SessionFactory sessionFactory=(SessionFactory)ac.getBean("sessionFactory"); // System.out.println("00001113333333----000->"+ sessionFactory); // System.out.println("00001113333333----000->"+ sessionFactory.openSession()); // return sessionFactory.openSession(); // System.out.println("0000000->"+ sessionFactory.getCurrentSession()); try { return sessionFactory.getCurrentSession(); } catch (Exception e) { e.getStackTrace(); } return null; } }
getCurrentSession()获得的sessoin不受Spring的事务管理?这个问题困扰了我好几天。
之前项目里没有spring,一切正常,dao里用到的session都是通过sessionFactory.getCurrentSession()获得的,手工启动事务,filter统一提交或回滚。 <br />说明hibernate的配置没有问题。 <br /> <br />然后引入了spring。 <br /> <br />spring的配置里的hibernate是这么初始化的,应该也无问题 <br /><pre name="code" class="java"> &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; &lt;property name="configLocation" value="classpath:hibernate.cfg.xml"/&gt; &lt;/bean&gt; </pre> <br /> <br />然后声明式事务管理 <br /><div class="quote_title">引用</div><div class="quote_div">&lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; <br /> &lt;property name="sessionFactory"&gt;&lt;ref bean="sessionFactory"/&gt;&lt;/property&gt; <br />&lt;/bean&gt; <br />&lt;tx:advice id="txAdvice" transaction-manager="transactionManager"&gt; <br /> &lt;tx:attributes&gt; <br /> &lt;tx:method name="*" propagation="REQUIRED"/&gt; <br /> &lt;tx:method name="get*" propagation="REQUIRED" read-only="true"/&gt; <br /> &lt;/tx:attributes&gt; <br />&lt;/tx:advice&gt; <br />&lt;aop:config&gt; <br /> &lt;aop:pointcut id="systemService" expression="execution(* com.orm.system.service.*.*(..))"/&gt; <br /> &lt;aop:advisor advice-ref="txAdvice" pointcut-ref="systemService"/&gt; <br />&lt;/aop:config&gt; <br /></div> <br /> <br />Dao都是继承自HibernateDaoSupport,接受spring注入的sessionFactory实例。切面是配置在service层的,service的方法里调用dao的方法。 <br /> <br />问题出来了。 <br /> <br />在任何一个Dao里面 <br />如果使用this.getSession()则session正常关闭,调用多次也没问题。 <br />如果使用this.getHibernateTemplate().getSessionFactory().getCurrentSession(),始终打开1个session并且不能关闭。 <br /> <br />我觉得如果使用this.getSession()正常,所以事务配置应该是没有问题的。 <br />而且有一点,如果是通过getCurrentSession()获得的session必须要beginTransaction,不然报错,而this.getSession()则不用。 <br /> <br />后来我配置了OpenSessionInViewFilter,发现这里打开和关闭的session和dao里面this.getSession()获得的session是同一个,而getCurrentSession()获得的不是同一个, <br />this.getSession().getTransaction().isActive() = true, <br />getCurrentSession().getTransaction().isActive() = false, <br /> <br />说明getCurrentSession()获得的session并不在事务管理里。 <br /> <br />我看了很多东西,一些是说getCurrentSession()在spring的事务管理,一些是说通过调用spring创建的sessionFactory的getCurrentSession()方法获得的session在spring的事务管理(难道还有不通过spring创建的sessionFactory?)。我做了一些测试,结果表明自始至终sessionFactory都只有一个实例。 <br /> <br /> <br />所以我得出结论,虽然sessionFactory受spring管理,但是直接从sessionFactory获取的session(不管是openSession还是getCurrentSession)不受spring的事务管理,是原生的Hibernate session。 <br /> <br />不知道我这样理解是否有问题,还是我哪里做错了得出了错误的结果?<br/><strong>问题补充</strong><br/>没有人研究过这个问题?还是太新手了不屑回答啊?
Spring和Strut2整合项目中报404错误
这个配置文件最后一段注释了的部分,一打开注释就直接404错误。这几个类写得都没什么问题啊,为什么一配置bean就出错呢? **补充:我找了半天发现问题是这样的:开始的时候我用的Spring的注释来配置bean,之后运行了一下项目出错了,我就删除了注释而改在applicationContext.xml中配置bean,然后其他地方的错改正了,但就是这几个配置的bean有问题。我试过了删除再重新配置也不行,难道是注释自动装配的bean会一直存在在IOC容器中,但不是每次web应用初始化都会重新建立IOC容器的吗?我试着删除了 原来的类重新创建了一个新类(类名变一下,bean的id也变一下)就可以了。这是什么原因?** **<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${db.user}"></property> <property name="password" value="${db.password}"></property> <property name="driverClass" value="${db.driverClass}"></property> <property name="jdbcUrl" value="${db.jdbcUrl}"></property> <property name="initialPoolSize" value="${db.initialPoolSize}"></property> <property name="maxPoolSize" value="${db.maxPoolSize}"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <property name="mappingLocations" value="classpath:com/gm/ssh/entities/*.hbm.xml"></property> </bean> <!-- <bean id="employeeDAO" class="com.gm.ssh.dao.EmployeeDAO"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="employeeService" class="com.gm.ssh.service.EmployeeService"> <property name="employeeDAO" ref="employeeDAO"></property> </bean> <bean id="employeeAction" class="com.gm.ssh.action.EmployeeAction" scope="prototype"> <property name="employeeService" ref="employeeService"></property> </bean> --> </beans>
java.lang.IllegalStateException: Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:91) at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:74) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:116) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:82) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:199) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:251) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:253) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:216) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:82) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:60) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:67) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/persistence/EntityListeners at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:540) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:260) at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:63) at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:83) ... 25 more Caused by: java.lang.NoClassDefFoundError: javax/persistence/EntityListeners at org.hibernate.cfg.annotations.reflection.JPAMetadataProvider.getDefaults(JPAMetadataProvider.java:96) at org.hibernate.annotations.common.reflection.java.JavaReflectionManager.getDefaults(JavaReflectionManager.java:226) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1385) at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:658) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:189) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1564) ... 40 more Caused by: java.lang.ClassNotFoundException: javax.persistence.EntityListeners at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 48 more 在SSH整合的时候遇见的错误,我的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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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"> <!-- 加载hibernate.cfg.xml 获得SessionFactory --> <bean name="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 确定配置文件的位置 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> </bean> <!-- 创建模板 --> <bean name="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- dao --> <bean name="userDao" class="com.shanmu.dao.impl.UserDaoImpl"> <property name="hibernateTemplate" ref="hibernateTemplate"></property> </bean> <!-- service --> <bean name="userService" class="com.shanmu.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> <!-- 事务管理 --> <!-- 事务管理器:HibernateTransactionManager --> <bean name="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 事务详情 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="register"/> </tx:attributes> </tx:advice> <!-- AOP编程 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.shanmu.service..*.*(..))"/> </aop:config> </beans> 但是一直报错,检查过代码问题没有错,检查过数据库,检查过路径,都没有错,网上的方法基本都试了,也没有错 求解
spring 事务
在做spring和hibernate进行整合的时候,进行单元测试的时候,发现这样的异常 org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection 在控制台已经没有任何错误,不知道谁什么原因,在google了半天也没找到原因。谢谢大家!数据库采用的是mysql [b]问题补充:[/b] 我把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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- <aop:aspectj-autoproxy/>基于注解方式进行aop开发 --> <context:annotation-config/><!-- 把注解注册到spring容器中 --> <!-- <context:component-scan base-package="bean"></context:component-scan>组件自动扫描 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.git.mm.mysql.Driver"/><!--驱动类 --> <property name="url" value="jdbc:mysql://localhost:3306/test" /><!--URL --> <property name="username" value="root"/><!--连接数据库用户名--> <property name="password" value="123456"/><!--连接数据库密码--> <property name="initialSize" value="1"/><!-- 连接池启动的初始值 --> <property name="maxActive" value="500"/><!-- 连接池的最大值 --> <property name="maxIdle" value="2"/><!-- 最大空闲值 ,经过高峰期后,恢复时候--> <property name="minIdle" value="2"/><!-- 最小空闲值--> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><!-- 把hibernate session给spring管理 --> <property name="dataSource" ref="dataSource"/><!-- 匹配上面的数据源 --> <property name="mappingResources"> <list> <value>bean/Person.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=true </value> </property> </bean> <!-- 对hibernate的事物进行管理,对session的创建等都会提交到事物中 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="personservice" class="bean.PersonService"></bean> <tx:annotation-driven transaction-manager="txManager"/><!-- 基于注解的方式申明事物 --> [b]问题补充:[/b] 因为我现在用的单元测试 还没有用到web容器 tomcat应该和tomcat没多大关系吧 呵呵! [b]问题补充:[/b] 应该不是测试类的问题吧 测试类是这样写的 private static PersonServiceInter bean; @BeforeClass public static void setUpBeforeClass() throws Exception { ApplicationContext ac=new ClassPathXmlApplicationContext("springBean.xml"); bean=(PersonServiceInter)ac.getBean("[color=red]personservice[/color]"); } @Test public void testAdd() { System.out.print("sss"); bean.add(new Person("jiba")); } personservice的类代码 @Transactional//注解方式申明事务 public class PersonService implements PersonServiceInter { @Resource private SessionFactory sessionFactory; //用resource注解方式注入,一般都是这个方式 public void add(Person person){ sessionFactory.getCurrentSession().persist(person);//得到spring容器当前管理的session //方法执行前打开事物,执行完后就自动关闭 }
使用spring data jpa出现的问题
今天在看慕课网关于jpa使用的视频,按照视频敲代码,可是却总报错,百度了下,说这错误是@Column和数据库的字段不对应,可是我连表都没有创建,这是什么情况? 报错如下: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [beans-new.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1589) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:554) 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.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at com.imooc.dao.TestEntityManagerFactory.setUp(TestEntityManagerFactory.java:18) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.junit.runner.JUnitCore.run(JUnitCore.java:157) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1225) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access$600(EntityManagerFactoryBuilderImpl.java:119) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:853) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843) at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842) at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:338) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1648) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1585) ... 35 more Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.imooc.domain.Employee at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:277) at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:224) at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775) at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3788) at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3742) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) ... 43 more 配置文件如下 <!--1 配置数据源--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="username" value="root"/> <property name="password" value="123456"/> <property name="url" value="jdbc:mysql:///spring_data"/> </bean> <!--2 配置EntityManagerFactory--> <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"/> </property> <property name="packagesToScan" value="com.imooc"/> <property name="jpaProperties"> <props> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> <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> 各位帮我看看这是什么错误,帮帮我,救救急!!!
spring,springmvc,hibernate整合
bean.xml [code="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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 打开spring对annotation的支持 --> <context:annotation-config/> <!-- 设定spring去那些包中找annotation --> <context:component-scan base-package="com.cms"></context:component-scan> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/cms_test" /> <property name="username" value="root" /> <property name="password" value="huhuawen@" /> <!-- 配置连接池的初始值 --> <property name="initialSize" value="1" /> <!-- 配置连接池的最大值 --> <property name="maxActive" value="500" /> <!-- 最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止 --> <property name="maxIdle" value="2" /> <!-- 最小空闲时,当连接少于 minIdle时会自动申请一些连接--> <property name="minIdle" value="1" /> <property name="maxWait" value="1000" /> </bean> <!-- 创建spring的sessionFactory工厂 --> <!-- 和hibernate4整合没有提供专门针对Annotion的类,直接在LocalSessionFactoryBean中已经集成 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" value="dataSource"'/> <!-- 设置spring取那个包中查找相应的实体类 --> <property name="packagesToScan" value="com.cms.common.model" /> <property name="hibernateProperties"> <props key="hibernate.dialect">org.hibernate.dialect.MYSQLDialect</props> <props key="hibernate.show_sql">true</props> <props key="hibernate.hbm2ddl.auto">update</props> <props key="hibernate.format_sql">false</props> </property> </bean> <!-- 配置spring的事务处理 --> <!-- 创建事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置AOP,spring是通过AOP来进行事务管理的 --> <aop:config> <!-- 以下的事务是在DAO中,但是通常都在Service来处理多个业务对象逻辑的关系,注入删除,更新等 就会导致数据不完整,所以事务不应该在DAO层处理,而应该在service层处理。 --> <aop:pointcut expression="allMethods" id="execution(* com.cms.common.dao.*.* (..))"/> <!-- 通过advisor来确定具体要加入事务控制的方法 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods"/> </aop:config> <!-- 配置那些方法要加入事务控制 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 --> <tx:attributes> <tx:method name="*" propagation="REQUIRED" read-only="true"/> <!-- 以下方法都可能的设计修改的方法。就无法设置为只读 --> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> </beans> [/code] 提示的错误说"sessionFactory"附近有错 property没有结束符,希望慧眼帮我看错来。提示的错误如下: Caused by: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 39 in XML document from class path resource [beans.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Element type "property" must be followed by either attribute specifications, ">" or "/>". at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243) at org.springframework.test.context.support.AbstractGenericContextLoader.loadBeanDefinitions(AbstractGenericContextLoader.java:233) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:117) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248) at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64) at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91) ... 31 more Caused by: org.xml.sax.SAXParseException: Element type "property" must be followed by either attribute specifications, ">" or "/>". at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:174) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:388) at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1411) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.seekCloseOfStartTag(XMLDocumentFragmentScannerImpl.java:1391) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:285) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2747) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283) at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388) ... 44 more Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.522 sec <<< FAILURE!
SSH框架整合中读取不到Spring的配置文件
求大神指导 下面附上源码: 错误提示: 严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: entity class not found: po.BizClaimVoucherDetail at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:608) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.hibernate.MappingException: entity class not found: po.BizClaimVoucherDetail at org.hibernate.mapping.PersistentClass.getMappedClass(PersistentClass.java:125) at org.hibernate.tuple.PropertyFactory.getGetter(PropertyFactory.java:191) at org.hibernate.tuple.PropertyFactory.buildIdentifierProperty(PropertyFactory.java:67) at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:135) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:485) at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:133) at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84) at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:286) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:863) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:782) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483) ... 21 more Caused by: java.lang.ClassNotFoundException: po.BizClaimVoucherDetail at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:192) at org.hibernate.mapping.PersistentClass.getMappedClass(PersistentClass.java:122) ... 34 more Spring配置文件的位置在SRC下创建了一个resource的文件夹 applicationContext.xml的配置文件源码: <!-- 创建sessionfactory回话工厂的bean 并读取Hibernate.cfg.xml的配置文件 --> <bean id = "sessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name = "configLocation" value="classpath:Hibernate.cfg.xml"></property> </bean> <!-- 实体类的bean 依赖注入--> <bean id="bizCheckResult" class="com.bdqn.zzt.jboa.entity.BizCheckResult"></bean> <bean id="bizClaimVoucher" class="com.bdqn.zzt.jboa.entity.BizClaimVoucher"></bean> <bean id="bizClaimVoucherDetail" class="com.bdqn.zzt.jboa.entity.BizClaimVoucherDetail"></bean> <bean id="sysDepartment" class="com.bdqn.zzt.jboa.entity.SysDepartment"></bean> <bean id="sysEmployee" class="com.bdqn.zzt.jboa.entity.SysEmployee"></bean> <bean id="sysPosition" class="com.bdqn.zzt.jboa.entity.SysPosition"></bean> <!--数据层的bean 依赖注入 --> <bean id = "userDaoImpl" class = "com.bdqn.zzt.jboa.dao.UserDaoImpl"> <property name = "sessionFactory" ref = "sessionFactory"></property> </bean> <!--业务层的bean 依赖注入 --> <bean id = "userBizImpl" class = "com.bdqn.zzt.jboa.biz.UserBizImpl"> <property name = "userDao" ref = "userDaoImpl"></property> </bean> <!-- 事务的管理 --> <bean id = "transactionManager" class = "org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name = "sessionFactory" ref = "sessionFactory"></property> </bean> <tx:advice id = "txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name = "get*" read-only="false"></tx:method> <tx:method name = "find*" ></tx:method> <tx:method name = "add*" ></tx:method> <tx:method name = "save*" ></tx:method> <tx:method name = "update*" ></tx:method> <tx:method name = "delete*" ></tx:method> <tx:method name = "merge" ></tx:method> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id = "serviceMethod" expression="execution(public * com.bdqn.zzt.jboa.biz.*.*(..))"></aop:pointcut> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"></aop:advisor> </aop:config> Web.xml的源码: <!--Spring 配置文件的存放位置 --> <!-- <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Spring 的监听器 WEB环境中启动Spring容器 --> <!-- <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!-- OpenSessionInView过滤器的配置 使回sesstion的管理范围增加--> <!-- <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> --> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <!--Strurs2的核心过滤器配置 --> <!-- <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
请问Spring如何在jar文件里面按文件夹加载配置文件?
一个Web应用有多个模块(假设有org和auth两个模块), 我希望为每个模块创建一个项目, 在项目中维护模块用到的配置文件. 然后将这些模块分别打包成jar放到web应用的WEB-INF/lib下. 现在用单元测试, 在Web应用中运行单元测试, 如果在Web应用的Build Path/Project中添加模块项目, 单元测试能够成功, 如果使用Build Path/Libraries添加模块jar文件, 运行单元测试失败. Spring中加载配置文件代码如下: [code="xml"] <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="mappingDirectoryLocations"> <list> <value>classpath*:/config/hibernate/app/</value> <value>classpath*:/config/hibernate/framework/</value> </list> </property> ... </bean> [/code] 每个jar包里面都有/config/hibernate/framework文件夹 错误信息: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'menuService' defined in URL [jar:file:/E:/home/workspaces/eclipse/simple-web/WebContent/WEB-INF/lib/auth.jar!/config/spring/app/services.xml]: Cannot resolve reference to bean 'defaultMediator' while setting bean property 'defautMediator'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultMediator' defined in class path resource [config/env/base-dao.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [config/persistence/hibernate.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: URL [jar:file:/E:/home/workspaces/eclipse/simple-web/WebContent/WEB-INF/lib/auth.jar!/config/hibernate/framework/] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/E:/home/workspaces/eclipse/simple-web/WebContent/WEB-INF/lib/auth.jar!/config/hibernate/framework/ 网上找到一个相关的讨论: http://forum.springframework.org/archive/index.php/t-10029.html 好像是说对于directory的加载必须是文件夹必须存在于文件系统中, jar下面的文件夹找不到.不知道这个问题有没有办法解决? 谢谢先! ps. 第一次提问, 如果有不当之处请各位包涵 [b]问题补充:[/b] 感谢czlonly的回答, 不过能不能写详细一点? 我刚才试了一下, 如果把配置文件改成 [code="xml"] <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="mappingLocations"> <list> <value>classpath*:/config/hibernate/framework/*.xml</value> </list> </property> ... </bean> [/code] 果然可以了
spring配置问题
我的StudentAction中通过spring注入sImpl,tomcat启动报创建StudentAction Bean实例错误: <span style="color: red">org.springframework.beans.InvalidPropertyException: Invalid property 'sImpl' of bean class [action.StudentAction]: No property 'sImpl' found</span>代码如下:<pre name="code" class="xml">web.xml: &lt;?xml version="1.0" encoding="iso-8859-1"?&gt; &lt;web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt; &lt;display-name&gt;Struts Examples Application&lt;/display-name&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/applicationContext.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;servlet&gt; &lt;servlet-name&gt;action&lt;/servlet-name&gt; &lt;servlet-class&gt;org.apache.struts.action.ActionServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;config&lt;/param-name&gt; &lt;param-value&gt; /WEB-INF/struts-config.xml &lt;/param-value&gt; &lt;/init-param&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;action&lt;/servlet-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;filter&gt; &lt;filter-name&gt;characterEncoding&lt;/filter-name&gt; &lt;filter-class&gt;filter.CharacterEncodingFilter&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;characterEncoding&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- The Usual Welcome File List --&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt; </pre><pre name="code" class="xml"> struts-config.xml: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"&gt; &lt;struts-config&gt; &lt;form-beans&gt; &lt;form-bean name="studentcourse" type="action.StudentCourseForm" /&gt; &lt;/form-beans&gt; &lt;action-mappings&gt; &lt;action path="/aa"&gt; &lt;forward name="success" path="/nihao.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/add" name="studentcourse"&gt; &lt;forward name="success" path="/add.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;/action-mappings&gt; &lt;controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/&gt; &lt;plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"&gt; &lt;set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml" /&gt; &lt;/plug-in&gt; &lt;/struts-config&gt; </pre><pre name="code" class="xml"> applicationContext.xml: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"&gt; &lt;bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"&gt; &lt;property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/&gt; &lt;property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:test"/&gt; &lt;property name="user" value="scott"/&gt; &lt;property name="password" value="zhoubl"/&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.Oracle9Dialect&lt;/prop&gt; &lt;prop key="show_sql"&gt;true&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="mappingResources"&gt; &lt;list&gt; &lt;value&gt;com/zhou/Student.hbm.xml&lt;/value&gt; &lt;value&gt;com/zhou/Course.hbm.xml&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="cImpl" class="daoImpl.ICourseImpl"&gt; &lt;property name="hibernateTemplate" ref="hibernateTemplate"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="sImpl" class="daoImpl.IStudentImpl"&gt; &lt;property name="hibernateTemplate" ref="hibernateTemplate"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;/bean&gt; &lt;!--struts配置--&gt; &lt;bean name="/aa" class="action.HelloAction"&gt;&lt;/bean&gt; &lt;bean name="/add" class="action.StudentAction"&gt; &lt;property name="sImpl" ref="sImpl"&gt;&lt;/property&gt; &lt;property name="cImpl" ref="cImpl"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </pre> <br /><br/><strong>问题补充</strong><br/><div class="quote_title">tangbo530 写道</div><div class="quote_div">注意修改相应的set方法</div><br />我属性设置为sImpl,方法为setSImpl(***),不也行吧!,但是我改为simpl就行了,我想知道一下其中的原理,希望知道的回答下,谢谢各位的回答!
springMVC怎么可以访问.do和.jsp
结果:访问.do报404错误;![图片说明](https://img-ask.csdn.net/upload/201905/06/1557130784_736858.png) 访问.jsp可以正常访问: ![图片说明](https://img-ask.csdn.net/upload/201905/06/1557130799_855496.png) 项目结构: ![图片说明](https://img-ask.csdn.net/upload/201905/06/1557131293_133479.png) 两个Controller: ![图片说明](https://img-ask.csdn.net/upload/201905/06/1557130985_851585.png) 这个返回值是json格式的。 ![图片说明](https://img-ask.csdn.net/upload/201905/06/1557131017_288476.png) 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" id="WebApp_ID" version="3.0"> <display-name>springmvc</display-name> <!-- Spring配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:bean.xml</param-value> </context-param> <!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- DispatcherServlet配置 --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 为了能够处理中文的post请求,再配置一个encodingFilter,以避免post请求中文出现乱码情况 --> <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> </web-app> ``` springmvc.xml ``` <context:component-scan base-package="com.web"></context:component-scan> <!-- <aop:aspectj-autoproxy proxy-target-class="true" /> --> <!-- 静态资源(js、image等)的访问 --> <mvc:default-servlet-handler /> <!-- 开启注解 --> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ``` bean.xml ``` <!-- 1. 数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 省略啦!!!! </bean> <!-- 2. Spring 对SessionFactory创建支持 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="mappingLocations"> <list> <value>classpath:com.pojo/*.hbm.xml</value> </list> </property> </bean> <!-- 3. 事务管理 --> <!-- a. 配置事务管理器类(切面类) --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- b. 事务通知 --> <tx:advice id="txAdvice" transaction-manager="txManager"> </tx:advice> <!-- c. Aop配置 --> <aop:config> <aop:pointcut expression="execution(* *Service.*(..))" id="pt" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt" /> </aop:config> <!-- 公用的配置 abstract="true" 表示是一个抽象的bean,不会被实例化; 可以被其他bean继承,就可以省略父bean定义多的属性 --> <bean id="baseDao" abstract="true"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- dao配置 --> <bean id="userDao" parent="baseDao" class="com.dao.UserDao"></bean> <!-- service配置 --> <bean id="userService" class="com.service.UserService"> <property name="userDao" ref="userDao"></property> </bean> <!-- controller配置 --> <bean id="userController" class="com.controller.UserController"> <property name="userService" ref="userService"></property> </bean> </beans> ``` 请问怎么可以访问.do和.jsp呢?
关于Spring事务传播级别PROPAGATION_NESTED的问题
一年前记得做过Nested传播级别的测试,当时结果是同Spring文档上介绍的一致的,即通过创建Savepoint实现嵌套事务,达到内层事务若抛出异常(unchecked exception)则回滚到savepoint处,但不影响外层事务;外层事务的回滚会一起回滚内层事务; 现在碰到的问题是,内层事务抛出unchecked exception,按照上述逻辑应该会回滚内层事务提交的数据,即便外层事务提交的情况下,但测试结果并非如此,外层事务一提交,内层方法创建的数据仍然被提交(debug显示内层事务已调用rollback),不知道是哪地方出了错误,现将测试代码贴上,请大家帮忙分析! [code="java"] <?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="orderDao" class="com.liuj.dao.hibernate.OrderHibernateDao" autowire="byType"/> <bean id="orderService" class="com.liuj.service.impl.OrderServiceImpl" autowire="byName"/> <bean id="productDao" class="com.liuj.dao.hibernate.ProductHibernateDao" autowire="byType"/> <bean id="productService" class="com.liuj.service.impl.ProductServiceImpl" autowire="byName"/> <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <list> <!-- beanNames for system.deployTargetAdvisor --> <value>orderService</value> <value>productService</value> </list> </property> <property name="interceptorNames"> <list> <value>system.transactionAdvisor</value> </list> </property> </bean> <bean id="system.transactionAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"> <property name="advice" ref="system.transactionInterceptor"/> <property name="pointcut" ref="system.transactionPointcut"/> </bean> <bean id="system.transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager"><ref bean="system.platformTransactionManager"/></property> <property name="transactionAttributes"> <props> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="query*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="innerSave*">PROPAGATION_NESTED</prop> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <bean id="system.transactionPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"> <property name="patterns"> <list> <value>com.liuj.service.OrderService.*</value> <value>com.liuj.service.ProductService.*</value> </list> </property> </bean> <!-- Hibernate SessionFactory --> <bean id="system.sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="system.datasource"/> <property name="annotatedClasses"> <list> <value>com.liuj.model.Order</value> <value>com.liuj.model.Product</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop> <prop key="hibernate.max_fetch_depth">3</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- Local DataSource that works in any environment --> <!-- <bean id="system.datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClassName}" /> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="initialPoolSize" value="${jdbc.initialPoolSize}" /> <property name="minPoolSize" value="${jdbc.minPoolSize}" /> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/> <property name="idleConnectionTestPeriod" value="300" /> <property name="breakAfterAcquireFailure" value="true" /> <property name="checkoutTimeout" value="100000" /> </bean> --> <bean id="system.datasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- <bean id="system.platformTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="system.sessionFactory"/> <property name="nestedTransactionAllowed" value="true"/> </bean> --> <!-- --> <bean id="system.platformTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="system.datasource"/> </bean> <bean id="system.propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> </beans> [/code] [code="java"] public class OrderHibernateDao extends HibernateDaoSupport implements OrderDao { public void save(Order order) { getHibernateTemplate().save(order); } } public class ProductHibernateDao extends HibernateDaoSupport implements ProductDao { public void save(Product product) { getHibernateTemplate().save(product); } } public class OrderServiceImpl implements OrderService { private ProductService productService; private OrderDao orderDao; public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } public void setProductService(ProductService productService) { this.productService = productService; } public void outerSave(Order order) { orderDao.save(order); try { productService.innerSave(); } catch (Exception e) { e.printStackTrace(); } } } public class ProductServiceImpl implements ProductService { private ProductDao productDao; public void setProductDao(ProductDao productDao) { this.productDao = productDao; } public void innerSave() { Product product = new Product(); product.setName("inner product"); productDao.save(product); if (true) { throw new RuntimeException("error happend"); } } } [/code] 测试代码如下 [code="java"] public class OrderServiceTest extends DependencyInjectionSpringContextTests { private OrderService orderService; @Test public void testSave() { Order order = new Order(); order.setName("outer order"); orderService.outerSave(order); } public void setOrderService(OrderService orderService) { this.orderService = orderService; } } [/code] 按照我的理解,ProductService.innerSave()方法抛出了runtime exception,那么结果应该是Order被保存,Product被回滚,但实际测试结果显示两个对象都被保存(debug显示save point被创建,并被rollback), why???
[讨论]Spring中事务管理与Hibernate自带事务管理冲突的一个问题
<p><span style="font-size: small;">场景是这样: <br>    有个提交申请单的操作,需三个动作:新增申请记录表记录、新增申请详单表记录,整个过程需完整,才能提交事务,其中一个过程失败,则需回到操作前状态,采用的是Spring声明式事务配置,但新增申请详单表记录时,由于插入数据量较大,发现用默认的HibernateTemplate里的save方法一条一条记录添加速度较慢,就使用了Hibernate批量插入,发现如果过程无错误,也会提示一个错误:java.lang.IllegalStateException: No value for key [org.hibernate.impl.SessionFactoryImpl@12421db] bound to thread [http-8080-Processor20] <br>,查了下估计是由于批量插入那边用了Hibernate自带的事务管理,释放了Hibernate下的session,和Spring配置的事务管理有冲突,有没有可以支持Spring自带事务管理,并且支持批量插入大量数据的方法,请教大家如何解决呢? </span></p> <p><span><font style=""> <p><br><span style="font-size: small;">附上大致代码:</span></p> </font></span></p> <p> </p> <p> </p> <p><span style="font-size: small;"> </span></p> <p><span style="font-size: small;">申请Service实现类大致Java代码:</span></p> <p> </p> <p> </p> <pre name="code" class="java">public void applyCard(CardInfo cardInfo, List&lt;CardDetail&gt; cardDetails){ //新增申请记录表记录 applyDAO.saveCardInfo(cardInfo); //新增申请详单表记录 applyDAO.batchSaveCardDetail(cardDetails); }</pre> <p> </p> <p><span style="font-size: small;">申请applyDAO实现类的batchSaveCardDetail方法(Hibernate批量插入):</span></p> <p><span style="font-size: small;"> </span></p> <p><span style="font-size: small;"><font style="" size="3"> <pre name="code" class="java">public void batchSaveCardDetail(List&lt;TCardInfo&gt; cardDetails) { Session session = this.getSession(); Transaction tx=null; try{ tx=session.beginTransaction(); for(int i=0;i&lt;cardDetails.size();i++){ session.save(cardDetails.get(i)); if(i%50 == 0){ session.flush(); session.clear(); } } tx.commit();//提交事务 }catch(Exception ex){ ex.printStackTrace(); tx.rollback();//出错则回滚 }finally{ session.close();//关闭session } }</pre> </font></span> </p> <pre name="code" class="java"></pre> <p><span style="font-size: small;"> <p>Spring相关配置如下:</p> <p> </p> <pre name="code" class="xml">&lt;!-- 应用的Spring里的Hibernate事务管理 --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;/bean&gt; &lt;!-- 配置事务拦截器--&gt; &lt;bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"&gt; &lt;property name="transactionManager" ref="transactionManager" /&gt; &lt;property name="transactionAttributes"&gt; &lt;props&gt; &lt;prop key="applyCard"&gt;PROPAGATION_REQUIRED&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- 根据事务拦截器为目标bean自动创建事务代理 --&gt; &lt;bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"&gt; &lt;property name="beanNames"&gt; &lt;list&gt; &lt;value&gt;applyService&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;property name="interceptorNames"&gt; &lt;list&gt; &lt;value&gt;transactionInterceptor&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- 申请Service --&gt; &lt;bean id="applyService" class="service.impl.ApplyServiceImpl"&gt; &lt;property name="applyDAO" ref="applyDAO"/&gt; &lt;/bean&gt;</pre> <p>  </p> <font style="" size="3"> <p> </p> </font></span></p> <p> </p>
Sping 构造方法注入 错误 java.lang.IllegalStateException: Failed to load ApplicationContext
错误信息 Mon Oct 08 10:39:48 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. Mon Oct 08 10:39:48 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. 10:39:48,985 ERROR TestContextManager:314 - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@d4602a] to prepare test instance [org.konghao.cms.service.TestIndexService@21ae6e73] java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99) at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122) at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105) at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206) Caused by: java.lang.IllegalArgumentException at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:110) at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:85) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1051) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:955) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:910) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:853) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:795) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:723) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1051) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:955) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248) at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64) at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91) ... 25 more 测试类代码 package org.konghao.cms.service; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.konghao.basic.model.SystemContext; import org.konghao.cms.service.IIndexService; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/beans.xml") public class TestIndexService { @Inject private IIndexService indexService; private String rp="D:\\teach_source\\class2\\j2EE\\cms2013\\cms-web\\src\\main\\webapp"; @Test public void testGenerateTop() { SystemContext.setRealPath(rp); indexService.generateTop(); } } package org.konghao.cms.service; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.konghao.basic.model.SystemContext; import org.konghao.basic.util.FreemarkerUtil; import org.konghao.cms.model.Channel; import org.konghao.cms.web.BaseInfoUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("indexService") public class IndexService implements IIndexService { private String ftlPath; private String outPath; private FreemarkerUtil util; @Autowired(required=true) public IndexService(String ftlPath, String outPath) { super(); if(util==null) { this.ftlPath = ftlPath; this.outPath = outPath; util=FreemarkerUtil.getInstance(ftlPath); } } private IChannelService channelService; public IChannelService getChannelService() { return channelService; } @Inject public void setChannelService(IChannelService channelService) { this.channelService = channelService; } @Override public void generateTop() { List<Channel> cs = channelService.listTopNavChannel(); Map<String, Object>root = new HashMap<String, Object>(); root.put("navs", cs); String outfile =SystemContext.getRealPath()+outPath+"/top.jsp"; util.fprint(root,"/top.ftl",outfile); } } bean.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:aop="http://www.springframework.org/schema/aop" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 打开Spring的Annotation支持 --> <context:annotation-config /> <!-- 设定Spring 去哪些包中找Annotation --> <context:component-scan base-package="org.konghao" /> <bean id="ftlPath" class="java.lang.String"> <constructor-arg value="/ftl"/> </bean> <bean id="outPath" class="java.lang.String"> <constructor-arg value="/jsp/template"/> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 配置连接池的初始值 --> <property name="initialSize" value="1" /> <!-- 连接池的最大值 --> <!-- <property name="maxActive" value="500"/> --> <!-- 最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止 --> <!-- <property name="maxIdle" value="2"/> --> <!-- 当最小空闲时,当连接少于minIdle时会自动去申请一些连接 --> <property name="minIdle" value="1" /> <property name="maxActive" value="100" /> <property name="maxIdle" value="20" /> <property name="maxWait" value="1000" /> </bean> <!--创建Spring的SessionFactory工厂 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 和hibernate4整合没有提供专门的针对Annotation的类,直接在LocalSessionFactoryBean中已经集成 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 设置Spring取那个包中查找相应的实体类 --> <property name="packagesToScan"> <value>org.konghao.cms.model</value> </property> <property name="hibernateProperties"> <!-- <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> --> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.format_sql">false</prop> </props> </property> </bean> <!-- 配置Spring的事务处理 --> <!-- 创建事务管理器--> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置AOP,Spring是通过AOP来进行事务管理的 --> <aop:config> <!-- 设置pointCut表示哪些方法要加入事务处理 --> <!-- 以下的事务是声明在DAO中,但是通常都会在Service来处理多个业务对象逻辑的关系,注入删除,更新等,此时如果在执行了一个步骤之后抛出异常 就会导致数据不完整,所以事务不应该在DAO层处理,而应该在service,这也就是Spring所提供的一个非常方便的工具,声明式事务 --> <aop:pointcut id="allMethods" expression="execution(* org.konghao.cms.service.*.*(..))" /> <!-- 通过advisor来确定具体要加入事务控制的方法 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" /> </aop:config> <!-- 配置哪些方法要加入事务控制 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 --> <tx:method name="*" propagation="REQUIRED" read-only="true"/> <!-- 以下方法都是可能设计修改的方法,就无法设置为只读 --> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="del*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="clear*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- <aop:config> <aop:aspect ref="indexService"> <aop:pointcut id="generateTopPoint" expression="execution(* org.kongkao.cms.service.channelService.add*(..))|| execution(* org.konghao.cms.service.ChannelService.del*(..))|| execution(* org.konghao.cms.service.ChannelService.update*(..))"/> <aop:after method="generteTop" pointcut-ref="generateTopPoint"/> </aop:aspect> </aop:config> --> </beans>
关于spring3.2.2配置事务问题
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>我的applicationContext.xml配置如下:</p> <pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "&gt; &lt;bean name="S3Impl" class="cn.xiaoxing.s3.dao.impl.S3Impl"&gt; &lt;property name="sessionFactory" ref="dbConfig"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&gt; &lt;property name="driverClassName"&gt; &lt;value&gt;com.mysql.jdbc.Driver&lt;/value&gt; &lt;/property&gt; &lt;property name="url"&gt; &lt;value&gt;jdbc:mysql://localhost:3306/test?useUnicode=true&amp;amp;characterEncoding=UTF-8&lt;/value&gt; &lt;/property&gt; &lt;property name="username" value="root"&gt;&lt;/property&gt; &lt;property name="password" value="123456"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;/bean&gt; &lt;tx:advice id="txAdvice" transaction-manager="txManager"&gt; &lt;tx:attributes&gt; &lt;tx:method name="get*" read-only="true" /&gt; &lt;tx:method name="*" /&gt; &lt;/tx:attributes&gt; &lt;/tx:advice&gt; &lt;aop:config&gt; &lt;aop:pointcut id="myPointCut" expression="execution(* cn.xiaoxing.s3.dao.impl.*.*(..))"/&gt; &lt;aop:advisor advice-ref="txAdvice" pointcut-ref="myPointCut"/&gt; &lt;/aop:config&gt; &lt;!-- 在Spring的application context中创建 SessionFactory --&gt; &lt;bean id="dbConfig" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt; &lt;!-- 资源注册 --&gt; &lt;property name="mappingResources"&gt; &lt;list&gt; &lt;value&gt;cn/xiaoxing/s3/vo/UserModel.hbm.xml&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;!-- 可选配置 --&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.format_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.current_session_context_class"&gt;thread&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> DAO实现部分代码如下:</p> <pre name="code" class="java">@Override public boolean create(UserModel um) { Session session = sessionFactory.getCurrentSession(); session.save(um); /*Transaction ts = session.beginTransaction(); try{ session.save(um); ts.commit(); }catch(Exception err){ ts.rollback(); err.printStackTrace(); return false; } */ return true; }</pre> <p> 报错信息如下:</p> <pre name="code" class="java">Exception in thread "main" org.hibernate.HibernateException: save is not valid without active transaction at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348) at $Proxy5.save(Unknown Source) at cn.xiaoxing.s3.dao.impl.S3Impl.create(S3Impl.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at $Proxy4.create(Unknown Source) at cn.xiaoxing.s3.Client.main(Client.java:20)</pre> <p> 我的问题是,如果按照上面代码执行的时候会报上面的错误,但如果我在DAO实现类中写hibernate事务后,就可以正常插入数据了,我想显然是因为配置的事务没有生效的缘故,自己折腾了半天也没有搞好,所以请各位帮忙指点。</p> <p>我用的版本:spring3.2.2   hibernate4</p> </div>
昨天正常,今天不正常的问题 Error creating bean with name 'sessionFactory'
[size=large]这样的配置用了好久了,一直没出状况,今天突然出状况了,而且重新集成ssh框架后也是同样的错误,郁闷中...,MyEclipse启动tomcat就报错,不知所谓何? 贴出来请教下有遇到此问题的大侠:[/size] 平台采用ssh框架,集成环境的jar包是用MyEclipse8.0M2自动创建, [img]http://dl.iteye.com/upload/attachment/188763/761d5160-fb8c-3b87-bbbb-c9e23a7c008f.png[/img] 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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 定义数据源Bean --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://127.0.0.1:3306/task_system?useUnicode=true&amp;characterEncoding=UTF-8"> </property> <property name="username" value="root"></property> <property name="password" value="1234"></property> </bean> <!--定义了Hibernate的SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.jdbc.batch_size">20</prop> </props> </property> <property name="mappingResources"> <list> <value>/pojo/UserDept.hbm.xml</value> <value>/pojo/UserEmployee.hbm.xml</value> <value>/pojo/UserJob.hbm.xml</value> </list> </property> </bean> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 报错: 严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.objectweb.asm.ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) [b]问题补充:[/b] 问题解决了,是我不知道什么时候把jsp页面的struts标签里加个html标签了,肯定是放错位置了,后来纠正后,又不小心还原了一下吧,所以没发现,今天看了楼下的朋友的答案,提醒了我,在jsp页面里把代码分段删除测试,终于发现问题之所在了。谢谢您的热心,多亏您提醒我。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
使用 Docker 部署 Spring Boot 项目
Docker 技术发展为微服务落地提供了更加便利的环境,使用 Docker 部署 Spring Boot 其实非常简单,这篇文章我们就来简单学习下。首先构建一个简单的 S...
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
刷了几千道算法题,这些我私藏的刷题网站都在这里了!
遥想当年,机缘巧合入了 ACM 的坑,周边巨擘林立,从此过上了"天天被虐似死狗"的生活… 然而我是谁,我可是死狗中的战斗鸡,智力不够那刷题来凑,开始了夜以继日哼哧哼哧刷题的日子,从此"读题与提交齐飞, AC 与 WA 一色 ",我惊喜的发现被题虐既刺激又有快感,那一刻我泪流满面。这么好的事儿作为一个正直的人绝不能自己独享,经过激烈的颅内斗争,我决定把我私藏的十几个 T 的,阿不,十几个刷题网...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
redis分布式锁,面试官请随便问,我都会
文章有点长并且绕,先来个图片缓冲下! 前言 现在的业务场景越来越复杂,使用的架构也就越来越复杂,分布式、高并发已经是业务要求的常态。像腾讯系的不少服务,还有CDN优化、异地多备份等处理。 说到分布式,就必然涉及到分布式锁的概念,如何保证不同机器不同线程的分布式锁同步呢? 实现要点 互斥性,同一时刻,智能有一个客户端持有锁。 防止死锁发生,如果持有锁的客户端崩溃没有主动释放锁,也要保证锁可以正常释...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Java世界最常用的工具类库
Apache Commons Apache Commons有很多子项目 Google Guava 参考博客
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员...
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC...
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下...
为什么要学数据结构?
一、前言 在可视化化程序设计的今天,借助于集成开发环境可以很快地生成程序,程序设计不再是计算机专业人员的专利。很多人认为,只要掌握几种开发工具就可以成为编程高手,其实,这是一种误解。要想成为一个专业的开发人员,至少需要以下三个条件: 1) 能够熟练地选择和设计各种数据结构和算法 2) 至少要能够熟练地掌握一门程序设计语言 3) 熟知所涉及的相关应用领域的知识 其中,后两个条件比较容易实现,而第一个...
Android 9.0 init 启动流程
阅读五分钟,每日十点,和您一起终身学习,这里是程序员Android本篇文章主要介绍Android开发中的部分知识点,通过阅读本篇文章,您将收获以下内容:一、启动流程概述一、 启动流程概述Android启动流程跟Linux启动类似,大致分为如下五个阶段。1.开机上电,加载固化的ROM。2.加载BootLoader,拉起Android OS。3.加载Uboot,初始外设,引导Kernel启动等。...
相关热词 c# 二进制截断字符串 c#实现窗体设计器 c#检测是否为微信 c# plc s1200 c#里氏转换原则 c# 主界面 c# do loop c#存为组套 模板 c# 停掉协程 c# rgb 读取图片
立即提问