Spring Batch/Spring Boot always auto-start my jobs - spring-boot

I'm using Spring Boot 1.3.3.RELEASE with Spring Batch 3.0.6.RELEASE and am having trouble getting Spring Batch/Spring Boot to not auto-start my jobs.
This question is similar to how to stop spring batch scheduled jobs from running at first time when executing the code?
I have the following test class:
#RunWith(SpringJUnit4ClassRunner.class)
#Configuration
#ComponentScan(useDefaultFilters = false,
includeFilters = #ComponentScan.Filter(value = GetMarkerViaSpringBatchApplicationTest.class,
type = FilterType.ASSIGNABLE_TYPE) )
#EnableBatchProcessing
//#IntegrationTest({"spring.batch.job.enabled=false"})
#EnableAutoConfiguration
#TestPropertySource(
locations = {"classpath:env.properties", "classpath:application.properties", "classpath:database.properties"},
properties = {"spring.batch.job.enabled=false"})
#SpringApplicationConfiguration(classes = {GetMarkerViaSpringBatchApplicationTest.class},
locations = {"classpath:**/GetMarkerViaSpringBatchApplicationTest-context.xml"})
public class GetMarkerViaSpringBatchApplicationTest {
#Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
#Test
public void testLaunchJob() throws Exception {
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
assertThat(jobExecution.getStatus()).isEqualTo(BatchStatus.COMPLETED);
}
}
In the same directory (package) as the test class I have config file GetMarkerViaSpringBatchApplicationTest-context.xml.
GetMarkerViaSpringBatchApplicationTest-context.xml contents:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="classpath:/META-INF/spring/get-marker-job-new.xml" />
<bean id="jobLauncherTestUtils" class="org.springframework.batch.test.JobLauncherTestUtils" />
<bean id="batchConfigurer" class="org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer">
<constructor-arg name="dataSource" ref="hsqlDataSource" />
</bean>
</beans>
get-marker-job-new.xml contents:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:batch="http://www.springframework.org/schema/batch" xmlns:task="http://www.springframework.org/schema/task"
xmlns:file="http://www.springframework.org/schema/integration/file" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration/file http://www.springframework.org/schema/integration/file/spring-integration-file.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="classpath:META-INF/spring/application-context.xml" />
<import resource="classpath:META-INF/spring/database.xml" />
<!-- The #EnableBatchProcessing on the main class sets up: job-repository, jobLauncher, and jobRepository -->
<!-- Spring Boot with Spring Batch doesn't like multiple DataSources since it doesn't know which one -->
<!-- to pick for Spring Batch. This class will therefore coerce to pick the proper HSQL dataSource. -->
<!-- See https://stackoverflow.com/questions/25540502/use-of-multiple-datasources-in-spring-batch -->
<bean id="batchConfigurer" class="org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer">
<constructor-arg name="dataSource" ref="hsqlDataSource" />
</bean>
<bean id="foo" class="myClass" />
<bean id="myTasklet" class="org.springframework.batch.core.step.tasklet.MethodInvokingTaskletAdapter">
<property name="targetObject" ref="myClass" />
<property name="targetMethod" value="deliver" />
</bean>
<batch:job id="batchJob" restartable="false">
<batch:step id="step1">
<batch:tasklet ref="myTasklet"/>
</batch:step>
</batch:job>
</beans>
application-context.xml contents:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<import resource="classpath:META-INF/spring/database.xml" />
<!-- load properties from config files -->
<context:property-placeholder location="classpath:env.properties,classpath:application.properties,classpath:database.properties" />
<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
</beans>
database.xml contents:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" 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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<bean id="myDataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.myco.driverClassName}" />
<property name="username" value="${jdbc.myco.username}" />
<property name="password" value="${jdbc.myco.encpassword}" />
<property name="jdbcUrl" value="${jdbc.myco.url}" />
<property name="maximumPoolSize" value="${jdbc.myco.pool.maxactive}" />
</bean>
<alias alias="dataSource" name="myDataSource" />
<bean id="hsqlDataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close" primary="true">
<property name="driverClassName" value="${jdbc.hsqldb.driverClassName}" />
<property name="username" value="${jdbc.hsqldb.username}" />
<property name="password" value="${jdbc.hsqldb.password}" />
<property name="jdbcUrl" value="${jdbc.hsqldb.url}" />
<property name="maximumPoolSize" value="${jdbc.hsqldb.pool.maxactive}" />
</bean>
</beans>
application.properties (in root dir which is also in the classpath):
spring.datasource.platform=sqlserver
spring.profiles.active=local
spring.batch.job.enabled=true
spring.batch.initializer.enabled=true
spring.batch.schema=classpath:org/springframework/batch/core/schema-hsqldb.sql
Note that spring.batch.job.enabled=true in the application.properties but false in the #IntegrationTest and the #TestPropertySource.
Whenever I set spring.batch.job.enabled=true in the application.properties regardless of trying various combos of spring.batch.job.enabled=false in the #IntegrationTest and the #TestPropertySource whenever I run this test the job is getting kicked off before the jobLauncherTestUtils.launchJob() gets called.
Logs from the run:
15:52:49,083 (o.s.test.context.support.AbstractDirtiesContextTestExecutionListener) - Before test class: context [DefaultTestContext#1733f619 testClass = GetMarkerViaSpringBatchApplicationTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#5461ef35 testClass = GetMarkerViaSpringBatchApplicationTest, locations = '{classpath:**/GetMarkerViaSpringBatchApplicationTest-context.xml}', classes = '{class xxx.myco.batch.client.GetMarkerViaSpringBatchApplicationTest}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:env.properties, classpath:application.properties, classpath:database.properties}', propertySourceProperties = '{spring.batch.job.enabled=false, marker=SELC_ALPHA_DONE, marker_date=2016/06/21, interval=1, times=1, is_fail=true, fail_path=${pkg.out}\\failed_alpha_report}', contextLoader = 'o.s.boot.test.SpringApplicationContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
15:52:49,099 (o.s.test.context.support.DependencyInjectionTestExecutionListener) - Performing dependency injection for test context [[DefaultTestContext#1733f619 testClass = GetMarkerViaSpringBatchApplicationTest, testInstance = xxx.myco.batch.client.GetMarkerViaSpringBatchApplicationTest#6769360f, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#5461ef35 testClass = GetMarkerViaSpringBatchApplicationTest, locations = '{classpath:**/GetMarkerViaSpringBatchApplicationTest-context.xml}', classes = '{class xxx.myco.batch.client.GetMarkerViaSpringBatchApplicationTest}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:env.properties, classpath:application.properties, classpath:database.properties}', propertySourceProperties = '{spring.batch.job.enabled=false, marker=SELC_ALPHA_DONE, marker_date=2016/06/21, interval=1, times=1, is_fail=true, fail_path=${pkg.out}\\failed_alpha_report}', contextLoader = 'o.s.boot.test.SpringApplicationContextLoader', parent = [null]]]].
15:52:50,572 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [database.properties]]
15:52:50,572 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [application.properties]]
15:52:50,572 (o.s.core.env.PropertySourcesPropertyResolver) - Found key 'spring.batch.job.enabled' in [class path resource [application.properties]] with type [String] and value 'false'
15:52:50,665 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [database.properties]]
15:52:50,665 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [application.properties]]
15:52:50,665 (o.s.core.env.PropertySourcesPropertyResolver) - Found key 'spring.batch.job.enabled' in [class path resource [application.properties]] with type [String] and value 'false'
15:52:50,665 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [database.properties]]
15:52:50,665 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [application.properties]]
15:52:50,665 (o.s.core.env.PropertySourcesPropertyResolver) - Found key 'spring.batch.job.enabled' in [class path resource [application.properties]] with type [String] and value 'false'
15:52:52,132 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [database.properties]]
15:52:52,132 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [application.properties]]
15:52:52,132 (o.s.core.env.PropertySourcesPropertyResolver) - Found key 'spring.batch.job.enabled' in [class path resource [application.properties]] with type [String] and value 'false'
15:53:00,861 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [database.properties]]
15:53:00,861 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [application.properties]]
15:53:00,861 (o.s.core.env.PropertySourcesPropertyResolver) - Found key 'spring.batch.job.enabled' in [class path resource [application.properties]] with type [String] and value 'false'
15:53:00,861 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [database.properties]]
15:53:00,861 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [application.properties]]
15:53:00,861 (o.s.core.env.PropertySourcesPropertyResolver) - Found key 'spring.batch.job.enabled' in [class path resource [application.properties]] with type [String] and value 'false'
15:53:00,861 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [database.properties]]
15:53:00,861 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [application.properties]]
15:53:00,861 (o.s.core.env.PropertySourcesPropertyResolver) - Found key 'spring.batch.job.enabled' in [class path resource [application.properties]] with type [String] and value 'false'
15:53:00,876 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [database.properties]]
15:53:00,876 (o.s.core.env.PropertySourcesPropertyResolver) - Searching for key 'spring.batch.job.enabled' in [class path resource [application.properties]]
15:53:00,876 (o.s.core.env.PropertySourcesPropertyResolver) - Found key 'spring.batch.job.enabled' in [class path resource [application.properties]] with type [String] and value 'false'
...
BatchAutoConfiguration#jobExplorer did not match
- #ConditionalOnMissingBean (types: o.s.batch.core.explore.JobExplorer; SearchStrategy: all) found the following [jobExplorer] (OnBeanCondition)
BatchAutoConfiguration#jobLauncherCommandLineRunner did not match
- #ConditionalOnMissingBean (types: o.s.boot.autoconfigure.batch.JobLauncherCommandLineRunner; SearchStrategy: all) found no beans (OnBeanCondition)
- #ConditionalOnProperty expected 'true' for properties spring.batch.job.enabled (OnPropertyCondition)
BatchAutoConfiguration.JpaBatchConfiguration did not match
- required #ConditionalOnClass classes not found: javax.persistence.EntityManagerFactory (OnClassCondition)
...
15:53:02,225 (o.s.test.context.cache.DefaultCacheAwareContextLoaderDelegate) - Storing ApplicationContext in cache under key [[MergedContextConfiguration#5461ef35 testClass = GetMarkerViaSpringBatchApplicationTest, locations = '{classpath:**/GetMarkerViaSpringBatchApplicationTest-context.xml}', classes = '{class xxx.myco.batch.client.GetMarkerViaSpringBatchApplicationTest}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:env.properties, classpath:application.properties, classpath:database.properties}', propertySourceProperties = '{spring.batch.job.enabled=false, marker=SELC_ALPHA_DONE, marker_date=2016/06/21, interval=1, times=1, is_fail=true, fail_path=${pkg.out}\\failed_alpha_report}', contextLoader = 'o.s.boot.test.SpringApplicationContextLoader', parent = [null]]]
15:53:02,256 (o.s.test.context.support.AbstractDirtiesContextTestExecutionListener) - Before test method: context [DefaultTestContext#1733f619 testClass = GetMarkerViaSpringBatchApplicationTest, testInstance = xxx.myco.batch.client.GetMarkerViaSpringBatchApplicationTest#6769360f, testMethod = testLaunchJob#GetMarkerViaSpringBatchApplicationTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#5461ef35 testClass = GetMarkerViaSpringBatchApplicationTest, locations = '{classpath:**/GetMarkerViaSpringBatchApplicationTest-context.xml}', classes = '{class xxx.myco.batch.client.GetMarkerViaSpringBatchApplicationTest}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:env.properties, classpath:application.properties, classpath:database.properties}', propertySourceProperties = '{spring.batch.job.enabled=false, marker=SELC_ALPHA_DONE, marker_date=2016/06/21, interval=1, times=1, is_fail=true, fail_path=${pkg.out}\\failed_alpha_report}', contextLoader = 'o.s.boot.test.SpringApplicationContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null], method annotated with #DirtiesContext [false] with mode [null].
15:53:04,669 (o.s.test.context.support.AbstractDirtiesContextTestExecutionListener) - After test method: context [DefaultTestContext#1733f619 testClass = GetMarkerViaSpringBatchApplicationTest, testInstance = xxx.myco.batch.client.GetMarkerViaSpringBatchApplicationTest#6769360f, testMethod = testLaunchJob#GetMarkerViaSpringBatchApplicationTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#5461ef35 testClass = GetMarkerViaSpringBatchApplicationTest, locations = '{classpath:**/GetMarkerViaSpringBatchApplicationTest-context.xml}', classes = '{class xxx.myco.batch.client.GetMarkerViaSpringBatchApplicationTest}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:env.properties, classpath:application.properties, classpath:database.properties}', propertySourceProperties = '{spring.batch.job.enabled=false, marker=SELC_ALPHA_DONE, marker_date=2016/06/21, interval=1, times=1, is_fail=true, fail_path=${pkg.out}\\failed_alpha_report}', contextLoader = 'o.s.boot.test.SpringApplicationContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null], method annotated with #DirtiesContext [false] with mode [null].
15:53:04,685 (o.s.test.context.support.AbstractDirtiesContextTestExecutionListener) - After test class: context [DefaultTestContext#1733f619 testClass = GetMarkerViaSpringBatchApplicationTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#5461ef35 testClass = GetMarkerViaSpringBatchApplicationTest, locations = '{classpath:**/GetMarkerViaSpringBatchApplicationTest-context.xml}', classes = '{class xxx.myco.batch.client.GetMarkerViaSpringBatchApplicationTest}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:env.properties, classpath:application.properties, classpath:database.properties}', propertySourceProperties = '{spring.batch.job.enabled=false, marker=SELC_ALPHA_DONE, marker_date=2016/06/21, interval=1, times=1, is_fail=true, fail_path=${pkg.out}\\failed_alpha_report}', contextLoader = 'o.s.boot.test.SpringApplicationContextLoader', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
I've read http://forum.spring.io/forum/spring-projects/batch/748038-i-do-not-want-enablebatchprocessing-to-launch-a-job and how to stop spring batch scheduled jobs from running at first time when executing the code? but can't seem to get the jobLauncher to NOT auto-start.
My understanding is that application.properties properties should be overriden by the 2 places I'm trying to set this directly within the Test but BatchAutoConfiguration doesn't seem to honor that override.
If I set spring.batch.job.enabled=false (or comment that property out) in the application.properties and try to drive it from either #IntegrationTest or #TestPropertySource it behaves as expected.
Is my understanding of the overriding of values incorrect?
Any help would be appreciated.

If you add application.properties to #TestPropertySource then it ends up overriding the other stuff. You don't need it there if you are using spring boot.

Related

Hibernate sql query format in console

I'm trying to log the sql queries i'm calling from a .xml file. The problem i'm facing is that when i see the log, it's not well formatted. Also, i don't know why it appears repeated...
[main] INFO org.dozer.DozerBeanMapper - Initializing a new instance of dozer bean mapper.
[main] INFO org.dozer.DozerBeanMapper - Initializing a new instance of dozer bean mapper.
[main] INFO org.springframework.orm.hibernate5.HibernateTransactionManager - Using DataSource [org.apache.commons.dbcp2.BasicDataSource#1f03fba0] of Hibernate SessionFactory for HibernateTransactionManager
[main] INFO org.springframework.aop.framework.CglibAopProxy - Unable to proxy method [public final void com.servicios.test.TestRestauranteManager.findProveedoresByIdRestaurante() throws com.servicios.util.exceptions.AlergenosException] because it is final: All calls to this method via a proxy will NOT be routed to the target instance.
[main] INFO org.springframework.test.context.transaction.TransactionContext - Began transaction (1) for test context [DefaultTestContext#436bd4df testClass = TestRestauranteManager, testInstance = com.servicios.test.TestRestauranteManager#6848a051, testMethod = findProveedoresByIdRestaurante#TestRestauranteManager, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#149b0577 testClass = TestRestauranteManager, locations = '{classpath:test-applicationContext.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.hibernate5.HibernateTransactionManager#5740ff5e]; rollback [true]
select restaurant0_."ID_RESTAURANTE" as ID_RESTA1_4_0_, restaurant0_."DESCRIPCION" as DESCRIPC2_4_0_, restaurant0_."ID_CADENA_RESTAURANTE" as ID_CADEN3_4_0_ from "RESTAURANTE" restaurant0_ where restaurant0_."ID_RESTAURANTE"=?
Hibernate: select restaurant0_."ID_RESTAURANTE" as ID_RESTA1_4_0_, restaurant0_."DESCRIPCION" as DESCRIPC2_4_0_, restaurant0_."ID_CADENA_RESTAURANTE" as ID_CADEN3_4_0_ from "RESTAURANTE" restaurant0_ where restaurant0_."ID_RESTAURANTE"=?
binding parameter [1] as [BIGINT] - [0]
I would like to have something like
[main] INFO org.dozer.DozerBeanMapper - Initializing a new instance of dozer bean mapper. [main] INFO org.dozer.DozerBeanMapper -
Initializing a new instance of dozer bean mapper. [main] INFO
org.springframework.orm.hibernate5.HibernateTransactionManager - Using
DataSource [org.apache.commons.dbcp2.BasicDataSource#1f03fba0] of
Hibernate SessionFactory for HibernateTransactionManager [main] INFO
org.springframework.aop.framework.CglibAopProxy - Unable to proxy
method [public final void
com.servicios.test.TestRestauranteManager.findProveedoresByIdRestaurante()
throws com.servicios.util.exceptions.AlergenosException] because it is
final: All calls to this method via a proxy will NOT be routed to the
target instance. [main] INFO
org.springframework.test.context.transaction.TransactionContext -
Began transaction (1) for test context [DefaultTestContext#436bd4df
testClass = TestRestauranteManager, testInstance =
com.servicios.test.TestRestauranteManager#6848a051, testMethod =
findProveedoresByIdRestaurante#TestRestauranteManager, testException =
[null], mergedContextConfiguration =
[MergedContextConfiguration#149b0577 testClass =
TestRestauranteManager, locations =
'{classpath:test-applicationContext.xml}', classes = '{}',
contextInitializerClasses = '[]', activeProfiles = '{}',
propertySourceLocations = '{}', propertySourceProperties = '{}',
contextLoader =
'org.springframework.test.context.support.DelegatingSmartContextLoader',
parent = [null]]]; transaction manager
[org.springframework.orm.hibernate5.HibernateTransactionManager#5740ff5e];
Hibernate: select
p."DESCRIPCION" as "descripcion",
p."ID_PROVEEDOR" as "idProveedor"
from
"RESTAURANTE_PROVEEDOR" rp
inner join
"PROVEEDOR" p
on rp."ID_PROVEEDOR" = p."ID_PROVEEDOR"
where
rp."ID_RESTAURANTE" = ? binding parameter [1] as [BIGINT] - [0]
My log4j.properties is the following:
log4j.rootLogger=INFO, stdout
log4j.logger.org.hibernate=INFO
log4j.logger.org.hibernate.SQL=TRACE
log4j.logger.org.hibernate.type=ALL
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.rootConsola.layout.ConversionPattern=(%d{dd/MM/yyyy-HH:mm:ss}) %-5p: %-40c{1} - %m%n
And in my ApplicationContext.xml I have this
...
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="packagesToScan" value="com.servicios.vo"/>
<property name="mappingLocations">
<list>
<value>classpath*:hibernate/queries/**/*.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
...
Thanks in advance!!
The hibernate.format_sql setting does not apply to Exception reasons when something happens and an Exception is thrown that includes a SQL fragment.
In other words, hibernate.format_sql only applies when Hibernate writes the SQL it's about to execute to the logs, not when it's included as part of some Exception reason.

No qualifying bean of type ... expected at least 1 bean which qualifies as autowire candidate for this dependency

I am trying to Inject Repository bean in this project, but keep getting:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.todo.services.TaskReader org.todo.services.AbstractTest.taskReader; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.todo.services.TaskReader] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.inject.Inject()}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.todo.services.TaskReader] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.inject.Inject()}
Project structure:
java
org.todo
model
repository
TaskRepository
services
TaskReader
impl
TaskReaderImpl
resources
config
applicationContext.cfg.xml
persistence.cfg.xml
META-INF
persistence.xml
test
org.todo.services
AbstractTest
Task Reader:
public interface TaskReader {
TaskItem findOne(long id);
List<TaskItem> findByOwner(ToDoUser toDoUser);
List<TaskItem> findAll();
}
Task Reader Implementation:
#Service
#Transactional(readOnly = true)
public class TaskReaderImpl implements TaskReader {
#Resource
private TaskRepository taskRepository;
#Inject
private UserReader userReader;
...
TaskRepository:
#Repository
public interface TaskRepository extends CrudRepository<Task, Long> {
#Query("select t from tasks t where t.owner = :user order by t.done, t.startedDate")
List<Task> findAllByOwner(#Param("user") User user);
#Query("select t from tasks t order by t.done, t.startedDate")
List<Task> findAll();
#Query("delete from tasks t where t.owner= :user")
void deleteAllByOwner(#Param("user") User user);
}
I am using TaskReader in some tests:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath*:config/applicationContext.cfg.xml")
public class AbstractTest {
#Inject
private TaskReader taskReader;
#Inject
private TaskWriter taskWriter;
#Inject
private UserWriter userWriter;
#Inject
private UserReader userReader;
applicationContext.cfg.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!--<context:annotation-config/>-->
<mvc:annotation-driven/>
<import resource="persistence.cfg.xml"/>
<context:component-scan base-package="org.todo.controller"/>
<context:component-scan base-package="org.todo.utils"/>
<context:component-scan base-package="org.todo.services"/>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
</bean>
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
persistence.cfg.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="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-2.5.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<jpa:repositories base-package="org.todo.model.repository"/>
<bean id="jpaVendor" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="H2"/>
</bean>
<jdbc:embedded-database id="dataSource" type="H2"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Drives transactions using local JPA APIs -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="dataSource" ref="dataSource"/>
<property name="rollbackOnCommitFailure" value="true"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitName" value="to-do-list"/>
<property name="jpaVendorAdapter" ref="jpaVendor"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
</beans>
Now I am given Error of autowired bean, but I couldn`t to find this error!
Full stackTrace:
Listener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
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:15)
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:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
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:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:202)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:65)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.todo.services.TaskReader org.todo.services.AbstractTest.taskReader; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.todo.services.TaskReader] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.inject.Inject()}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
... 24 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.todo.services.TaskReader] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.inject.Inject()}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:988)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
... 26 more
11:55:10,850 DEBUG ProfileValueUtils:68 - Retrieved #PtProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:376)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
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:15)
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:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
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:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:202)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:65)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.todo.services.TaskReader org.todo.services.AbstractTest.taskReader; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.todo.services.TaskReader] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.inject.Inject()}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
... 24 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.todo.services.TaskReader] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.inject.Inject()}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:988)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
... 26 more
11:55:10,894 DEBUG ProfileValueUtils:68 - Retrieved #ProfileValueSourceConfiguration [null] for test class [org.todo.services.TaskServicesTest]
11:55:10,895 DEBUG ProfileValueUtils:80 - Retrieved Profile11:55:11,135 TRACE TestContextManager:427 - afterTestClass(): class [class org.todo.services.TaskServicesTest]
11:55:11,137 DEBUG DirtiesContextTestExecutionListener:138 - After test class: context [[TestContext#1974736 testClass = TaskServicesTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#c44deb testClass = TaskServicesTest, locations = '{classpath*:config/applicationContext.cfg.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]], dirtiesContext [false].
11:55:11,155 INFO GenericApplicationContext:1042 - Closing org.springframework.context.support.GenericApplicationContext#c1d5a3: startup date [Mon Jan 27 11:55:10 EET 2014]; root of context hierarchy
11:55:11,156 TRACE GenericApplicationContext:332 - Publishing event in org.springframework.context.support.GenericApplicationContext#c1d5a3: org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.support.GenericApplicationContext#c1d5a3: startup date [Mon Jan 27 11:55:10 EET 2014]; root of context hierarchy]
11:55:11,158 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'lifecycleProcessor'
11:55:11,159 INFO DefaultListableBeanFactory:444 - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7c49e3: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Disconnected from the target VM, address: '127.0.0.1:55631', transport: 'socket'
project source: github.

Unable to Import persistence.xml within applicationContext.xml file

I'm using eclipse juno IDE
I have Java application which have src folder. within the folder I have:
1) applicationContext.xml
2) persistence.xml
I also have DBInterface and i implemented it with JPA.
Now in the applicationContext.xml file I have a bean for the JPA implemention.
When I tried to inject the bean i got an excpetion that said something like "No Persistence Provider was found".
So I tried to import the persistence file within the applicationContext file but i'm getting another exception.
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/spring-aop-2.5.xsd"
xmlns:context="http://www.springframework.org/schema/context/spring-context-2.5.xsd"
xmlns:flow="http://www.springframework.org/schema/webflow-config/spring-webflow-config-1.0.xsd"
xmlns:jms="http://www.springframework.org/schema/jms/spring-jms-2.5.xsd"
xmlns:jee="http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"
xmlns:lang="http://www.springframework.org/schema/lang/spring-lang-2.5.xsd"
xmlns:osgi="http://www.springframework.org/schema/osgi/spring-osgi.xsd"
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
xmlns:util="http://www.springframework.org/schema/util/spring-util-2.5.xsd"
xmlns:p="http://www.springframework.org/schema/p"
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/spring-aop-2.5.xsd http://www.springframework.org/schema/aop/spring-aop-2.5.xsd/spring-spring-aop-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/context/spring-context-2.5.xsd/spring-spring-context-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/webflow-config/spring-webflow-config-1.0.xsd http://www.springframework.org/schema/webflow-config/spring-webflow-config-1.0.xsd/spring-spring-webflow-config-1.0.xsd-2.5.xsd
http://www.springframework.org/schema/jms/spring-jms-2.5.xsd http://www.springframework.org/schema/jms/spring-jms-2.5.xsd/spring-spring-jms-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/jee/spring-jee-2.5.xsd/spring-spring-jee-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd http://www.springframework.org/schema/lang/spring-lang-2.5.xsd/spring-spring-lang-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/osgi/spring-osgi.xsd http://www.springframework.org/schema/osgi/spring-osgi.xsd/spring-spring-osgi.xsd-2.5.xsd
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/tx/spring-tx-2.5.xsd/spring-spring-tx-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/util/spring-util-2.5.xsd http://www.springframework.org/schema/util/spring-util-2.5.xsd/spring-spring-util-2.5.xsd-2.5.xsd">
<bean id="JPA" class="pack.jpa.JPAQueries"/>
<import resource="persistence.xml"/>
</beans>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit transaction-type="RESOURCE_LOCAL" name="MyJPA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>pack.bl.Travels</class>
<class>pack.bl.Example</class>
<properties> <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/taxis"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
</persistence-unit>
mainClass
public class Program {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
DBInterface dao = (DBInterface)context.getBean("JPA",JPAQueries.class);
dao.retrieveRecords();
}
Exception
Exception in thread "main"
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration
problem: Failed to import bean definitions from relative location [persistence.xml]
Offending resource: class path resource [applicationContext.xml]; nested exception is
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration
problem: Unable to locate Spring NamespaceHandler for XML schema namespace
[http://java.sun.com/xml/ns/persistence]
Offending resource: class path resource [persistence.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:271)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:196)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:181)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:140)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:111)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
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.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:527)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:441)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at pack.program.Program.main(Program.java:16)
Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://java.sun.com/xml/ns/persistence]
Offending resource: class path resource [persistence.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:317)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1428)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1421)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:190)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:140)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:111)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
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.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:255)
... 20 more
Your attempt to use persistence.xml as a Spring config makes absolutely no sense, because persistence.xml is not a Spring config.
If you want to use JPA with Spring, you need to put persistence.xml into META-INF folder inside your source folder, and declare LocalContainerEntityManagerFactory in applicationContext.xml:
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name = "persistenceUnitName" value = "MyJPA" />
</bean>
Then you can inject EntityManager into your Spring bean using #PersistenceContext:
#PersistenceContext
private EntityManager em;
See also:
13.5 JPA
It should be imported as follows:
<import resource="classpath:META-INF/persistence.xml"/>
assuming the persistence.xml is present in META-INF directory which is a top-level directory in one of your jars on the classpath.
Ok, I Solved this..
What i did is to put the persistence.xml file within the META-INF folder
as vikdor and axtavt suggested. but in the application context i didn't import any file..
just wrote this
<bean id="JPA" class="pack.jpa.JPAQueries"/>
and its work!

Autowiring issue with JUnit in a Spring Data JPA environment

i have issues with #autowired in my unit tests.
here are the relevant classes and xml files:
The Service Class:
#Service(value = "statusService")
public class StatusService implements DefaultService<Status> {
#Autowired(required = true)
private StatusRepository statusRepository;
public void save(Status value) {
statusRepository.save(value);
}
}
The Interface:
public interface DefaultService<T> {
#Transactional
void save(T value);
}
(i also tested a non generic interface, but the result was the same.)
The Test Class:
#ContextConfiguration(locations={"**/WEB-INF/applicationContext.xml", "**/WEB-INF/hibernate-context.xml"})
#RunWith(SpringJUnit4ClassRunner.class)
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#Transactional
public class StatusServiceTest
{
#Autowired
private StatusService statusService;
#Test
public void test()
{
Status s = new Status();
s.setDescription("desc");
s.setStatus("status");
statusService.save(s);
}
}
The Application Context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
For example #Controller and #Service. Make sure to set the correct base-package-->
<context:component-scan base-package="at.jba.ticketbox" />
<jpa:repositories base-package="at.jba.ticketbox.repositories" />
<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />
<!-- Configures the annotation-driven Spring MVC Controller programming model.
Note that, with Spring 3.0, this tag works in Servlet MVC only! -->
<mvc:annotation-driven />
<!-- Load Hibernate related configuration -->
<import resource="hibernate-context.xml" />
</beans>
The Hibernate-Context
<?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: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-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="/WEB-INF/spring.properties" />
<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
<!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
<!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
p:packagesToScan="at.jba.ticketbox"/> -->
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driver}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"
/>
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" p:dataSource-ref="dataSource" />
<!-- JPA Entity Manager Factory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:persistenceXmlLocation="META-INF/persistence.xml"
p:persistenceUnitName="springJpaPersistenceUnit_TEST" />
<!-- bean post-processor for JPA annotations -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>
and the stack trace:
INFO : org.springframework.test.context.TestContextManager - #TestExecutionListeners is not present for class [class at.jba.ticketbox.service.interfaces.DefaultServiceTest]: using defaults.
INFO : org.springframework.context.support.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext#63afe611: startup date [Tue Mar 13 15:19:44 CET 2012]; root of context hierarchy
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5543bd5c: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#4ad70ab0] to prepare test instance [at.jba.ticketbox.service.interfaces.DefaultServiceTest#6bfecf32]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'at.jba.ticketbox.service.interfaces.DefaultServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private at.jba.ticketbox.service.StatusService at.jba.ticketbox.service.interfaces.DefaultServiceTest.sr; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [at.jba.ticketbox.service.StatusService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
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:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
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:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
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:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private at.jba.ticketbox.service.StatusService at.jba.ticketbox.service.interfaces.DefaultServiceTest.sr; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [at.jba.ticketbox.service.StatusService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [at.jba.ticketbox.service.StatusService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 28 more
INFO : org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext#63afe611: startup date [Tue Mar 13 15:19:44 CET 2012]; root of context hierarchy
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5543bd5c: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
i tried to autowire the interface (the generic one too) instead of the Service Class, cause i´ve read that there probably are issues.
i tried it with an #Resource, same stacktrace
i tried writting a non generic interface
...
i find it strange that the, application runs perfectly on an tomcat server as a web application. no problems there saving and deleting Objects. I still don´t understand why the tests aren´t working.
plz help ;) thx
By default, locations parameter of #ContextConfiguration annotation is assuming classpath: protocol, so you need to explicitly specify file: protocol when loading files not in the classpath, e.g. context located within WEB-INF folder:
#ContextConfiguration(locations={
"file:**/WEB-INF/applicationContext.xml", "file:**/WEB-INF/hibernate-context.xml"})
#RunWith(SpringJUnit4ClassRunner.class)
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#Transactional
public class StatusServiceTest
...

Spring can't find bean named entityManagerFactory

I have a web application that uses spring and hibernate for JPA support, but when I open my Index page this exception happens:
http://pastebin.com/0X1GG9GQ
But I think my applicationContext.xml is well configured, but I'm posting it anyways just to be sure:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<!-- properties file for jdbc database access details / -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- enabling annotation driven configuration / -->
<context:annotation-config />
<context:component-scan base-package="com.maegul" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceUnitName" value="maegul"></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}" />
</beans>
I really don't know what's wrong, I've been changing little things to no avail, any help would be greatly appreciated.
EDIT (Long Stack in pastebin for easier reading...)
Changed some things in the ApplicationContext.xml and now I get a different stack trace:
INFO - Server - jetty-7.5.0.v20110901
INFO - tandardDescriptorProcessor - NO JSP Support for {}, did not find {}
INFO - / - Initializing Spring root WebApplicationContext
INFO - ContextLoader - Root WebApplicationContext: initialization started
INFO - XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Sun Nov 06 13:22:53 COT 2011]; root of context hierarchy
INFO - XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/ApplicationContext.xml]
INFO - DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#40871449: defining beans [maegulApplication,itemService,userService,cartItemDao,mediaItemDao,mediaSourceDao,passwordDao,userDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor]; root of factory hierarchy
INFO - DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#40871449: defining beans [maegulApplication,itemService,userService,cartItemDao,mediaItemDao,mediaSourceDao,passwordDao,userDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor]; root of factory hierarchy
ERROR - ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.maegul.data.dao.impl.MediaItemDao com.maegul.service.implementation.ItemFindService.mediaItemDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mediaItemDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0
Rest of stack here: http://pastebin.com/u82n3C5n
I see that the Annotations I made are getting recognized, but it looks like it can't still find an entityManagerFactory. One thing I've seen is that maybe instead of using #PersistenceContext should I use #PersistenceUnit in my EntityManager fields, but I dont know...
EDIT 2
All my DAO implementations look like this:
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import com.maegul.data.dao.AbstractDAO;
import com.maegul.data.entities.MediaItem;
#Repository(value = "mediaItemDao")
public class MediaItemDaoImpl extends AbstractDAO<MediaItem> implements
MediaItemDao {
#PersistenceContext
private EntityManager em;
/*
* (non-Javadoc)
*
* #see com.maegul.data.dao.DAO#getEntityManager()
*/
public EntityManager getEntityManager() {
return em;
}
/*
* (non-Javadoc)
*
* #see com.maegul.data.dao.DAO#getClazz()
*/
public Class<MediaItem> getClazz() {
return MediaItem.class;
}
/*
* (non-Javadoc)
*
* #see com.maegul.data.dao.impl.MediaItemDao#findByName(java.lang.String)
*/
public MediaItem findByName(String name) {
Query q = getEntityManager().createQuery(
"select u from " + getClazz() + " where u.name = :name");
q.setParameter("name", name);
return (MediaItem) q.getSingleResult();
}
/*
* (non-Javadoc)
*
* #see com.maegul.data.dao.impl.MediaItemDao#findByType(java.lang.String)
*/
#SuppressWarnings("unchecked")
public List<MediaItem> findByType(String type) {
Query q = getEntityManager().createQuery("select u from " + getClazz() + " where u.type = :type");
q.setParameter("type", type);
return q.getResultList();
}
}
EDIT 3
This is the AbstractDAO class: http://pastebin.com/f2BQG9RE
And this is the DAO interface, which is implemented by AbstractDAO: http://pastebin.com/h7dAHTTC
and this is the Interface MEdiaItemDao:
import java.util.List;
import com.maegul.data.dao.DAO;
import com.maegul.data.entities.MediaItem;
public interface MediaItemDao extends DAO<MediaItem>{
MediaItem findByName(String name);
List<MediaItem> findByType(String type);
}
It only needed a project clean, so I did and it fixed it.

Resources