Использую версии Spring 5.0.8., Hibernate 5.3.4. Собираю web приложение в gradle. Задача: настроить конфигурацию Hibernate в Spring.
При запуске выскакивает ConfigurationException
в тестах. (Caused by: org.hibernate.internal.util.config.ConfigurationException at MySqlDaoFactoryTest)
. Что я делаю не так, буду рад любой помощи.
файл web-context.xml
(располагается в директории webapp/WEB-INF
):
<?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:jpa="http://www.springframework.org/schema/data/jpa"
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-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"
default-autowire="byName">
<context:component-scan base-package="main" />
<context:annotation-config/>
<context:property-placeholder location="classpath:conn.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<bean id="MySqlDaoFactory" class="dao.MySqlDaoFactory">
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.c3p0.minPoolSize">1</prop>
<prop key="hibernate.c3p0.maxPoolSize">10</prop>
<prop key="hibernate.c3p0.max_statement">100</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
</props>
</property>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
<property name="annotatedClasses">
<list>
<value>domain.Student</value>
<value>domain.Subjects</value>
</list>
</property>
</bean>
<bean id="session" class="dao.MySqlDaoFactory"
factory-bean="MySqlDaoFactory" factory-method="getSession">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
...
DAO:
public class MySqlDaoFactory extends DAOFactory{
@Autowired
private SessionFactory sessionFactory;
private Session session = null;
public Session getSession() throws DAOException {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
} catch (Exception e) {
throw new DAOException("Error of session", e);
}
return session;
}
public StudentDao getStudentDAO(Session session){
return new MySqlStudentDao(session);
}
public SubjectDao getSubjectDAO(Session session){
return new MySqlSubjectDao(session);
}
}
зависимости в gradle:
compile group: 'jstl', name: 'jstl', version:'1.2'
compile group: 'mysql', name: 'mysql-connector-java', version:'5.1.46'
compile group: 'org.springframework', name: 'spring-core', version: '5.0.8.RELEASE'
compile group: 'org.springframework', name: 'spring-context', version: '5.0.8.RELEASE'
compile group: 'org.springframework', name: 'spring-beans', version: '5.0.8.RELEASE'
compile group: 'org.springframework', name: 'spring-webmvc', version: '5.0.8.RELEASE'
compile group: 'org.springframework', name: 'spring-web', version: '5.0.8.RELEASE'
compile group: 'org.springframework', name: 'spring-orm', version: '5.0.8.RELEASE'
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-core', version: '9.0.10'
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-logging-juli', version: '9.0.0.M6'
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-jasper', version: '9.0.10'
compile group: 'com.bmuschko', name: 'gradle-tomcat-plugin', version: '2.5'
compile group: 'org.hibernate', name: 'hibernate-core', version: '5.3.4.Final'
compile group: 'org.hibernate', name: 'hibernate-c3p0', version: '5.3.4.Final'
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '5.3.4.Final'
compile group: 'org.apache.commons', name: 'commons-dbcp2', version: '2.5.0'
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version:'3.1.0'
testCompile 'org.testng:testng:6.14.3'
Тест:
public class MySqlDaoFactoryTest {
static DAOFactory daoFactory;
@BeforeClass
static void initAll() {
daoFactory = new MySqlDaoFactory();
}
@Test
void connectionTest() throws DAOException {
Session session = daoFactory.getSession();
assertNotNull(session, "Connection failed");
}
}
Ошибка:
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.apache.commons.dbcp.BasicDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/web-context.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1380)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:660)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:627)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1489)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1012)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:739)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4643)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5109)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:742)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:718)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:703)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:986)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1858)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:772)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:426)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1585)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:308)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:424)
at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:367)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:966)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1427)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1417)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:682)
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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1309)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1138)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:274)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:437)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1428)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1372)
... 51 more
файл conn.properties:
driver = com.mysql.jdbc.Driver
username = root
password = root
url = jdbc:mysql://localhost:3306/student_db?useSSL=false
Вы можете использовать менеджер источников данных от Spring:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
Современные решения для бизнеса: как облачные и виртуальные технологии меняют рынок
Виртуальный выделенный сервер (VDS) становится отличным выбором
Java документация гласит, что джинерики работают с помощью механизма "стирания", те
Используя сторонние библиотеки, или нативные библиотеки Java, можно сделать цветной шрифт в терминале? Может что-то наподобие printf? И есть возможность...
интересует момент: для каждого репозитори - свой сервис? И потом уже создавать общий сервис, связывая другие сервисы, или же, все таки можно...