Spring returns new instance each time I use instance variable - spring

I got a wired problem.
Here is my object definition.
package unittest.prototypetest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component("valObject")
#Scope("prototype")
public class ValueObject {
private String value1;
private String value2;
//... getter and setter omitted.
}
And I defined the component scan tag as below:
<context:component-scan base-package="unittest" scoped-proxy="targetClass" />
Then I tried to get its instance via ApplicatioinContext,
//ApplicationContextHelper is a class written by me to easily create ApplicationContext
ValueObject valObject = ApplicationContextHelper.getBean("valObject");
valObject.setValue1("v1");
valObject.setValue2("v2");
System.out.println(valObject.getValue1());
System.out.println(valObject.getValue2());
The most wired result is shown below:
2013-01-15_14:04:02.245| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Returning cached instance of singleton bean 'valObject'
2013-01-15_14:04:02.246| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.246| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2013-01-15_14:04:02.250| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2013-01-15_14:04:02.250| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2013-01-15_14:04:02.252| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Finished creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.295| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.296| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Finished creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.296| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.296| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Finished creating instance of bean 'scopedTarget.valObject'
null
2013-01-15_14:04:02.296| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.297| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Finished creating instance of bean 'scopedTarget.valObject'
null
You can see each time I use valObject instance, Spring did create a new instance for my access.
so that the system out prints null, although I set value.
Did I do something wrong ? Please advise, thanks a lot.

You have set the scope to prototype, wich is a non-singleton. Read more about it here.

Related

How to disable spring-boot DataSource auto configuration

I would like to disable auto-configuration of my DataSource in spring, as in some environments we may not have the datasource deployed yet and want to use lazy initialization. I am having trouble finding a way to do this. I am on spring.boot.version 2.5.9.
I have found many others trying to achieve the same thing, such as Disable Spring Boot Configuration. However they all mention using the exclusions below:
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
or the similar properties option. However this is not working for me. I have tried removing many classes that i have seen initialize my DataSource Bean but i can't get to the bottom of it. (my current code below)
#SpringBootApplication(exclude = {
JdbcTemplateAutoConfiguration.class,
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
AopAutoConfiguration.class,
ConfigurationPropertiesAutoConfiguration.class,
LifecycleAutoConfiguration.class,
PersistenceExceptionTranslationAutoConfiguration.class,
DataSourceHealthContributorAutoConfiguration.class,
HibernateJpaAutoConfiguration.class})
I have also added a screenshot of the dependencies in my project related to spring.
And here are some of my logs at startup currently. translationJobDB is my DataSource that i am trying to stop from being initalized on startup.
2022-08-07 13:16:57,533 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'viewResolver'
2022-08-07 13:16:57,534 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'viewResolver' via factory method to bean named 'org.springframework.beans.factory.support.DefaultListableBeanFactory#6c6d76f7'
2022-08-07 13:16:57,543 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration'
2022-08-07 13:16:57,544 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'applicationAvailability'
2022-08-07 13:16:57,549 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.actuate.autoconfigure.availability.AvailabilityHealthContributorAutoConfiguration'
2022-08-07 13:16:57,554 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration'
2022-08-07 13:16:57,555 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'standardJacksonObjectMapperBuilderCustomizer'
2022-08-07 13:16:57,557 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties'
2022-08-07 13:16:57,563 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'standardJacksonObjectMapperBuilderCustomizer' via factory method to bean named 'org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#34b56ac0'
2022-08-07 13:16:57,564 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'standardJacksonObjectMapperBuilderCustomizer' via factory method to bean named 'spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties'
2022-08-07 13:16:57,567 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration'
2022-08-07 13:16:57,568 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration'
2022-08-07 13:16:57,570 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'parameterNamesModule'
2022-08-07 13:16:57,576 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration'
2022-08-07 13:16:57,578 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration'
2022-08-07 13:16:57,579 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'jsonComponentModule'
2022-08-07 13:16:57,588 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.actuate.autoconfigure.web.servlet.ServletManagementContextAutoConfiguration'
2022-08-07 13:16:57,590 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'servletWebChildContextFactory'
2022-08-07 13:16:57,591 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'managementServletContext'
2022-08-07 13:16:57,592 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'managementServletContext' via factory method to bean named 'management.endpoints.web-org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties'
2022-08-07 13:16:57,595 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.actuate.autoconfigure.health.HealthEndpointAutoConfiguration'
2022-08-07 13:16:57,596 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration'
2022-08-07 13:16:57,600 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties'
2022-08-07 13:16:57,605 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration' via constructor to bean named 'spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties'
2022-08-07 13:16:57,607 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'management.info-org.springframework.boot.actuate.autoconfigure.info.InfoContributorProperties'
2022-08-07 13:16:57,611 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'pathMappedEndpoints'
2022-08-07 13:16:57,615 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'pathMappedEndpoints' via factory method to bean named 'servletEndpointDiscoverer'
2022-08-07 13:16:57,615 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'pathMappedEndpoints' via factory method to bean named 'webEndpointDiscoverer'
2022-08-07 13:16:57,616 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'pathMappedEndpoints' via factory method to bean named 'controllerEndpointDiscoverer'
2022-08-07 13:16:57,620 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration'
2022-08-07 13:16:57,621 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.actuate.autoconfigure.metrics.integration.IntegrationMetricsAutoConfiguration'
2022-08-07 13:16:57,622 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.actuate.autoconfigure.metrics.jdbc.DataSourcePoolMetricsAutoConfiguration'
2022-08-07 13:16:57,623 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration'
2022-08-07 13:16:57,625 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'gsonBuilder'
2022-08-07 13:16:57,627 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'standardGsonBuilderCustomizer'
2022-08-07 13:16:57,629 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'spring.gson-org.springframework.boot.autoconfigure.gson.GsonProperties'
2022-08-07 13:16:57,638 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'standardGsonBuilderCustomizer' via factory method to bean named 'spring.gson-org.springframework.boot.autoconfigure.gson.GsonProperties'
2022-08-07 13:16:57,640 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'gsonBuilder' via factory method to bean named 'standardGsonBuilderCustomizer'
2022-08-07 13:16:57,674 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'gson'
2022-08-07 13:16:57,675 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'gson' via factory method to bean named 'gsonBuilder'
2022-08-07 13:16:57,786 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration'
2022-08-07 13:16:57,787 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.http.GsonHttpMessageConvertersConfiguration'
2022-08-07 13:16:57,788 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration'
2022-08-07 13:16:57,789 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.actuate.autoconfigure.metrics.web.client.RestTemplateMetricsConfiguration'
2022-08-07 13:16:57,789 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'restTemplateExchangeTagsProvider'
2022-08-07 13:16:57,791 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'metricsRestTemplateCustomizer'
2022-08-07 13:16:57,793 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'metricsRestTemplateCustomizer' via factory method to bean named 'simpleMeterRegistry'
2022-08-07 13:16:57,794 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'metricsRestTemplateCustomizer' via factory method to bean named 'restTemplateExchangeTagsProvider'
2022-08-07 13:16:57,794 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'metricsRestTemplateCustomizer' via factory method to bean named 'management.metrics-org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties'
2022-08-07 13:16:57,800 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.actuate.autoconfigure.metrics.web.tomcat.TomcatMetricsAutoConfiguration'
2022-08-07 13:16:57,802 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'tomcatMetricsBinder'
2022-08-07 13:16:57,802 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'tomcatMetricsBinder' via factory method to bean named 'simpleMeterRegistry'
2022-08-07 13:16:57,804 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration$JmsTemplateConfiguration'
2022-08-07 13:16:57,805 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration$JmsTemplateConfiguration' via constructor to bean named 'spring.jms-org.springframework.boot.autoconfigure.jms.JmsProperties'
2022-08-07 13:16:57,806 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'jmsTemplate'
2022-08-07 13:16:57,807 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'jmsTemplate' via factory method to bean named 'sqsConnectionFactory'
2022-08-07 13:16:57,847 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration$MessagingTemplateConfiguration'
2022-08-07 13:16:57,849 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'jmsMessagingTemplate'
2022-08-07 13:16:57,851 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'jmsMessagingTemplate' via factory method to bean named 'spring.jms-org.springframework.boot.autoconfigure.jms.JmsProperties'
2022-08-07 13:16:57,851 DEBUG [main] [Log Context: ] org.springframework.beans.factory.support.ConstructorResolver:808 Autowiring by type from bean name 'jmsMessagingTemplate' via factory method to bean named 'jmsTemplate'
2022-08-07 13:16:57,889 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration'
2022-08-07 13:16:57,890 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.sql.init.DataSourceInitializationConfiguration'
2022-08-07 13:16:57,892 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'dataSourceScriptDatabaseInitializer'
2022-08-07 13:16:57,894 DEBUG [main] [Log Context: ] o.s.beans.factory.support.DefaultSingletonBeanRegistry:225 Creating shared instance of singleton bean 'translationJobDB'

Spring transactions - isolation and propagation understanding

I am exploring spring transactions and after going through the spring docs and the following link i still have few questions. If I have a parent method with Propogation.REQUIRED which is calling 3 methods with Propogation.REQUIRES_NEW as follows:
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public Contact saveContactInSteps(Contact contact, String newFirstName, String newLastName, Date bDate) throws Exception {
contact.setFirstName(newFirstName);
try {
updateContactFirstName(contact);
} catch (Exception e) {
LOG.error("Contact first name could not be saved !!");
e.printStackTrace();
throw e;
}
contact.setLastName(newLastName);
try {
updateContactLastName(contact);
} catch (Exception e) {
LOG.error("Contact Last name could not be saved !!");
e.printStackTrace();
throw e;
}
contact.setBirthDate(bDate);
updateContactBday(contact);
return contact;
}
public Contact saveById(Contact contact) {
sessionFactory.getCurrentSession().saveOrUpdate(contact);
LOG.info("Contact " + contact + " saved successfully");
return contact;
}
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public Contact updateContactFirstName(Contact contact) throws Exception {
throw new Exception("Cannot update first name");
//sessionFactory.getCurrentSession().saveOrUpdate(contact);
//LOG.info("Contact First name saved successfully");
//return contact;
}
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public Contact updateContactLastName(Contact contact) throws Exception {
throw new Exception("Cannot update last name");
//sessionFactory.getCurrentSession().saveOrUpdate(contact);
//LOG.info("Contact " + contact + " saved successfully");
//return contact;
}
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public Contact updateContactBday(Contact contact) {
sessionFactory.getCurrentSession().saveOrUpdate(contact);
LOG.info("Contact Birth Date saved successfully");
return contact;
}
Whenever i process the parent method i.e. saveContactInSteps, even the last name is getting updated in database. I am not sure how that is happening. If i throw the exception from first child method nothing gets updated. Is it because of the fact that i am setting the attributes i.e. names and birthdate in the parent method ? Even if i am setting the attributes in the parent method, i am not letting the parent method complete as well. Does the isolation level play any part here ? I believe it's for concurrent transactions ? Is there something i am missing ?
EDIT 1:
After going through the article i did realize what i was missing. I needed AOP proxies in place which i have added as follows:
<aop:config>
<aop:pointcut
expression="execution(* org.pack.spring.transactions.ContactService.*(..))"
id="updateOperation" />
<aop:advisor pointcut-ref="updateOperation" advice-ref="saveUpdateAdvice" />
</aop:config>
<tx:advice id="saveUpdateAdvice">
<tx:attributes>
<tx:method name="update*" propagation="REQUIRES_NEW" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
Log output is as follows:
01:23:57.535 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.550 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
01:23:57.552 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'saveUpdateAdvice'
01:23:57.552 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'saveUpdateAdvice'
01:23:57.552 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Eagerly caching bean 'saveUpdateAdvice' to allow for resolving potential circular references
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean '(inner bean)#56ac5c80'
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.557 [main] DEBUG o.s.t.i.NameMatchTransactionAttributeSource - Adding transactional method [update*] with attribute [PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT,-Exception]
01:23:57.557 [main] DEBUG o.s.t.i.NameMatchTransactionAttributeSource - Adding transactional method [save*] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-Exception]
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.558 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean '(inner bean)#56ac5c80'
01:23:57.558 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'saveUpdateAdvice'
01:23:57.558 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'saveUpdateAdvice'
01:23:57.568 [main] DEBUG o.s.a.a.a.AspectJAwareAdvisorAutoProxyCreator - Creating implicit proxy for bean 'springTxContactService' with 0 common interceptors and 3 specific interceptors
01:23:57.575 [main] DEBUG o.s.aop.framework.CglibAopProxy - Creating CGLIB proxy: target source is SingletonTargetSource for target object [org.pack.ch9.spring.transactions.hibernate.home.ContactService#598260a6]
01:23:57.654 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.save(org.pack.ch9.spring.transactions.hibernate.home.Contact)
01:23:57.654 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.saveContactInSteps' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.655 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.saveContactInSteps(org.pack.ch9.spring.transactions.hibernate.home.Contact,java.lang.String,java.lang.String,java.util.Date) throws java.lang.Exception
01:23:57.655 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.findAll' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
01:23:57.656 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public java.util.List org.pack.ch9.spring.transactions.hibernate.home.ContactService.findAll()
01:23:57.656 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.findById' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
01:23:57.656 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.findById(java.lang.Long)
01:23:57.657 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.saveById' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.657 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.saveById(org.pack.ch9.spring.transactions.hibernate.home.Contact)
01:23:57.657 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.updateContactFirstName' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.657 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.updateContactFirstName(org.pack.ch9.spring.transactions.hibernate.home.Contact) throws java.lang.Exception
01:23:57.658 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.updateContactLastName' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.658 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.updateContactLastName(org.pack.ch9.spring.transactions.hibernate.home.Contact) throws java.lang.Exception
01:23:57.658 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.updateContactBday' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.658 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.updateContactBday(org.pack.ch9.spring.transactions.hibernate.home.Contact)
01:23:57.659 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.setSessionFactory' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.660 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public void org.pack.ch9.spring.transactions.hibernate.home.ContactService.setSessionFactory(org.hibernate.SessionFactory)
01:23:57.661 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.getSessionFactory' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.661 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.hibernate.SessionFactory org.pack.ch9.spring.transactions.hibernate.home.ContactService.getSessionFactory()
01:23:57.661 [main] DEBUG o.s.aop.framework.CglibAopProxy - Found 'equals' method: public boolean java.lang.Object.equals(java.lang.Object)
01:23:57.662 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public java.lang.String java.lang.Object.toString()
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.event.internalEventListenerFactory'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'saveUpdateAdvice'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'sessionFactory'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'hibernateProperties'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor'
01:23:57.699 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionalEventListenerFactory'
01:23:57.699 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
01:23:57.746 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor#21d1b321]
01:23:57.747 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
01:23:57.750 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
01:23:57.752 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'springTxContactService'
01:23:57.755 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
01:23:57.762 [main] DEBUG o.s.o.h.HibernateTransactionManager - Creating new transaction with name [org.pack.ch9.spring.transactions.hibernate.home.ContactService.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
01:23:57.962 [main] DEBUG o.s.o.h.HibernateTransactionManager - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
01:23:57.964 [main] DEBUG o.s.o.h.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
01:23:57.965 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/springorm]
01:23:57.977 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Setting JDBC Connection [com.mysql.jdbc.JDBC4Connection#2a685eba] read-only
01:23:57.983 [main] DEBUG o.s.o.h.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection#2a685eba]
Hibernate: select distinct contact0_.ID as ID1_0_0_, contacttel1_.ID as ID1_2_1_, hobby3_.HOBBY_ID as HOBBY_ID1_3_2_, contact0_.BIRTH_DATE as BIRTH_DA2_0_0_, contact0_.FIRST_NAME as FIRST_NA3_0_0_, contact0_.LAST_NAME as LAST_NAM4_0_0_, contact0_.VERSION as VERSION5_0_0_, contacttel1_.CONTACT_ID as CONTACT_5_2_1_, contacttel1_.TEL_NUMBER as TEL_NUMB2_2_1_, contacttel1_.TEL_TYPE as TEL_TYPE3_2_1_, contacttel1_.VERSION as VERSION4_2_1_, contacttel1_.CONTACT_ID as CONTACT_5_2_0__, contacttel1_.ID as ID1_2_0__, hobbies2_.CONTACT_ID as CONTACT_2_1_1__, hobbies2_.HOBBY_ID as HOBBY_ID1_1_1__ from contact contact0_ left outer join contact_tel_detail contacttel1_ on contact0_.ID=contacttel1_.CONTACT_ID left outer join contact_hobby_detail hobbies2_ on contact0_.ID=hobbies2_.CONTACT_ID left outer join hobby hobby3_ on hobbies2_.HOBBY_ID=hobby3_.HOBBY_ID where contact0_.ID=?
01:23:58.099 [main] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction commit
01:23:58.101 [main] DEBUG o.s.o.h.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[org.pack.ch9.spring.transactions.hibernate.home.Contact#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#7]],collectionKeys=[CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.contactTelDetails#6], CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.hobbies#6]]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
01:23:58.103 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Resetting read-only flag of JDBC Connection [com.mysql.jdbc.JDBC4Connection#2a685eba]
01:23:58.103 [main] DEBUG o.s.o.h.HibernateTransactionManager - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[org.pack.ch9.spring.transactions.hibernate.home.Contact#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#7]],collectionKeys=[CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.contactTelDetails#6], CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.hobbies#6]]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] after transaction
01:23:58.117 [main] DEBUG o.s.o.h.HibernateTransactionManager - Creating new transaction with name [org.pack.ch9.spring.transactions.hibernate.home.ContactService.saveContactInSteps]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:58.117 [main] DEBUG o.s.o.h.HibernateTransactionManager - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
01:23:58.117 [main] DEBUG o.s.o.h.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
01:23:58.117 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/springorm]
01:23:58.127 [main] DEBUG o.s.o.h.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection#1daf3b44]
01:23:58.127 [main] DEBUG o.s.o.h.HibernateTransactionManager - Found thread-bound Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
01:23:58.127 [main] DEBUG o.s.o.h.HibernateTransactionManager - Participating in existing transaction
01:23:58.127 [main] ERROR o.p.c.s.t.h.home.ContactService - Contact First name could not be saved !!
01:23:58.127 [main] ERROR o.p.c.s.t.h.home.ContactService - Contact Last name could not be saved !!
01:23:58.137 [main] INFO o.p.c.s.t.h.home.ContactService - Contact Birth Date saved successfully
01:23:58.138 [main] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction commit
01:23:58.138 [main] DEBUG o.s.o.h.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[org.pack.ch9.spring.transactions.hibernate.home.Contact#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#7]],collectionKeys=[CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.contactTelDetails#6], CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.hobbies#6]]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
Note - I have removed the #Transactional annotations from the methods as i am relying on proxy to achieve the same.
From the logs, it seems that the proxies are getting created but again as pointed out in the comment, will the 3 methods invoked from saveContactInSteps not have a transaction against them as mentioned in the documentation :
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with #Transactional. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. #PostConstruct
Is there a way to get around this ? Is AspectJ the only solution ?

Neo4jConfiguration has circular references

I'm using spring-data-neo4j in a spring-boot application. I did the configuration as recommended in spring.io guides and many other places by inheriting Neo4jConfiguration class. This works when the database location is hardcoded in the provided examples. However when I want to use a placeholder for retrieving the database location from a property file it's not retrieved and I get null. Here's the code
#Configuration
#EnableNeo4jRepositories(basePackageClasses = {MyRepository.class})
public class Neo4jConfig extends Neo4jConfiguration {
#Value("${neo4j.location}")
private String neo4jDatabaseLocation;
#Bean
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory()
.newEmbeddedDatabase(neo4jDatabaseLocation);
}
...
This normally works in any other config class but not in this one because of the Neo4jConfiguration class has some several methods marked with #Autowired. This causes circular reference and it's not initialized properly. This can be seen in the logs:
2014-09-06 20:59:45.168 DEBUG 4665 --- [ main] o.s.b.f.annotation.InjectionMetadata : Registered injected element on class [c.m.f.Neo4jConfig$$EnhancerBySpringCGLIB$$7165d752]: AutowiredFieldElement for private javax.validation.Validator org.springframework.data.neo4j.config.Neo4jConfiguration.validator
2014-09-06 20:59:45.169 DEBUG 4665 --- [ main] o.s.b.f.annotation.InjectionMetadata : Registered injected element on class [c.m.f.Neo4jConfig$$EnhancerBySpringCGLIB$$7165d752]: AutowiredMethodElement for public void org.springframework.data.neo4j.config.Neo4jConfiguration.setConversionService(org.springframework.core.convert.ConversionService)
2014-09-06 20:59:45.169 DEBUG 4665 --- [ main] o.s.b.f.annotation.InjectionMetadata : Registered injected element on class [c.m.f.Neo4jConfig$$EnhancerBySpringCGLIB$$7165d752]: AutowiredMethodElement for public void org.springframework.data.neo4j.config.Neo4jConfiguration.setGraphDatabaseService(org.neo4j.graphdb.GraphDatabaseService)
2014-09-06 20:59:45.169 DEBUG 4665 --- [ main] o.s.b.f.annotation.InjectionMetadata : Registered injected element on class [c.m.f.Neo4jConfig$$EnhancerBySpringCGLIB$$7165d752]: AutowiredFieldElement for private java.lang.String c.m.f.Neo4jConfig.neo4jDatabaseLocation
2014-09-06 20:59:45.169 DEBUG 4665 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Eagerly caching bean 'c.m.f.Neo4jConfig' to allow for resolving potential circular references
2014-09-06 20:59:45.171 DEBUG 4665 --- [ main] o.s.b.f.annotation.InjectionMetadata : Processing injected method of bean 'c.m.f.Neo4jConfig': AutowiredFieldElement for private javax.validation.Validator org.springframework.data.neo4j.config.Neo4jConfiguration.validator
2014-09-06 20:59:45.182 DEBUG 4665 --- [ main] o.s.b.f.annotation.InjectionMetadata : Processing injected method of bean 'c.m.f.Neo4jConfig': AutowiredMethodElement for public void org.springframework.data.neo4j.config.Neo4jConfiguration.setConversionService(org.springframework.core.convert.ConversionService)
2014-09-06 20:59:45.183 DEBUG 4665 --- [ main] o.s.b.f.annotation.InjectionMetadata : Processing injected method of bean 'c.m.f.Neo4jConfig': AutowiredMethodElement for public void org.springframework.data.neo4j.config.Neo4jConfiguration.setGraphDatabaseService(org.neo4j.graphdb.GraphDatabaseService)
2014-09-06 20:59:45.184 DEBUG 4665 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'graphDatabaseService'
2014-09-06 20:59:45.184 DEBUG 4665 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating instance of bean 'graphDatabaseService'
2014-09-06 20:59:45.185 DEBUG 4665 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2014-09-06 20:59:45.185 DEBUG 4665 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2014-09-06 20:59:45.188 DEBUG 4665 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Returning eagerly cached instance of singleton bean 'c.m.f.Neo4jConfig' that is not fully initialized yet - a consequence of a circular reference
As you can see what I'm trying to achieve here is not to hardcode the database location. Is there any workaround for this circular reference problem? Or maybe any other way of configuring it? As this is a spring-boot application, I don't have any Xml configuration and if it's possible I want to keep it that way.
Have you tried passing in the neo4jDatabaseLocation as a parameter:
#Configuration
#EnableNeo4jRepositories(basePackageClasses = {MyRepository.class})
public class Neo4jConfig extends Neo4jConfiguration {
#Bean
public GraphDatabaseService graphDatabaseService(#Value("${neo4j.location}") String neo4jDatabaseLocation) {
return new GraphDatabaseFactory()
.newEmbeddedDatabase(neo4jDatabaseLocation);
}
...
}
Proposed suggestions did not work for the spring framework version I am using. As a workaround, I defined the GraphDatabaseService bean in another configuration file which does not extend Neo4jConfiguration. Note that this Neo4jConfig class is needed regardless.

#Autowired fails with JUnit & Spring

Really need help. I used JUnit(4.6) plus Spring(3.0.5) for unit testing. When I tried to autowire a service object in my test class, I got a NoSuchBeanDefinitionException.
The JUnit code:
package com.aaa.service.impl;
#ContextConfiguration(locations = { "classpath:/spring/applicationContext.xml",
"classpath:/spring/applicationContext-aop.xml",
"classpath:/spring/applicationContext-dao.xml",
"classpath:/spring/applicationContext-service.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
public class TestManageTargetServiceImpl {
#Autowired
ManageTargetServiceImpl manageTargetServiceImpl;
#Test
public void testQueryFinancialMonthList() {
List<Map<String, Object>> value = new ArrayList<Map<String, Object>>();
ManageTargetDao manageTargetDao = mock(ManageTargetDao.class);
when(manageTargetDao.queryFinancialMonthList()).thenReturn(value);
manageTargetServiceImpl.setManageTargetDao(manageTargetDao);
// I hope it return null
assertNull(manageTargetServiceImpl.queryFinancialMonthList());
}
}
The applicationContext-service.xml code:
<context:annotation-config />
<bean id="manageTargetService" class="com.aaa.service.impl.ManageTargetServiceImpl">
<property name="manageTargetDao" ref="manageTargetDao"></property>
</bean>
The error track:
00:51:28,625 ERROR main context.TestContextManager:324 - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#882dfc] to prepare test instance [com.aaa.service.impl.TestManageTargetServiceImpl#ce2db0]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.aaa.service.impl.TestManageTargetServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.aaa.service.impl.ManageTargetServiceImpl com.aaa.service.impl.TestManageTargetServiceImpl.manageTargetServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.aaa.service.impl.ManageTargetServiceImpl] 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)}
Some log:
00:51:26,828 DEBUG main context.TestContextManager:282 - beforeTestClass(): class [class com.aaa.service.impl.TestManageTargetServiceImpl]
00:51:26,828 DEBUG main annotation.ProfileValueUtils:68 - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.aaa.service.impl.TestManageTargetServiceImpl]
00:51:26,828 DEBUG main annotation.ProfileValueUtils:80 - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.aaa.service.impl.TestManageTargetServiceImpl]
00:51:26,828 DEBUG main context.TestContextManager:315 - prepareTestInstance(): instance [com.aaa.service.impl.TestManageTargetServiceImpl#ce2db0]
00:51:26,843 DEBUG main support.DependencyInjectionTestExecutionListener:73 - Performing dependency injection for test context [[TestContext#e0eb3f testClass = TestManageTargetServiceImpl, locations = array<String>['classpath:/spring/applicationContext.xml', 'classpath:/spring/applicationContext-aop.xml', 'classpath:/spring/applicationContext-dao.xml', 'classpath:/spring/applicationContext-service.xml'], testInstance = com.aaa.service.impl.TestManageTargetServiceImpl#ce2db0, testMethod = [null], testException = [null]]].
00:51:26,843 DEBUG main support.AbstractGenericContextLoader:75 - Loading ApplicationContext for locations [classpath:/spring/applicationContext.xml,classpath:/spring/applicationContext-aop.xml,classpath:/spring/applicationContext-dao.xml,classpath:/spring/applicationContext-service.xml].
00:51:26,968 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext.xml]
00:51:27,187 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext-aop.xml]
00:51:27,312 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext-dao.xml]
00:51:27,421 INFO main xml.XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [spring/applicationContext-service.xml]
00:51:27,453 INFO main support.GenericApplicationContext:456 - Refreshing org.springframework.context.support.GenericApplicationContext#16c14e7: startup date [Tue Jan 01 00:51:27 NZDT 2013]; root of context hierarchy
00:51:27,718 INFO main config.PropertyPlaceholderConfigurer:177 - Loading properties file from class path resource [jdbc.properties]
00:51:27,796 INFO main support.DefaultListableBeanFactory:555 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2938d8: defining beans [loggingAop,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,service,loginDao,manageTargetDao,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,txManager,txAdvice,txDAO,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0,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,loginService,manageTargetService]; root of factory hierarchy
Guessing here - but given that injection of a class type ManageTargetServiceImpl is failing, I think the reason is that a proxy is getting created for ManageTargetServiceImpl and so the type of the bean will not be ManageTargetServiceImpl anymore but the interface of that class.
from Biju Kunjummen
Look at your property id. It should be manageTargetServiceImpl in your applicationContext-service.xml
Change it to this:
<bean id="manageTargetServiceImpl" class="com.aaa.service.impl.ManageTargetServiceImpl">
<property name="manageTargetDao" ref="manageTargetDao"></property>
</bean>

Spring #Autowired OK on JUnit, NPE on main class

I have a open source project hosted at this github. I am facing a weird scenario. I found many people who could make #Autowired Spring annotation work on their main classes but not on their JUnit test classes. My problem is the other way around. I can successfully use #Autowired in my JUnit test class but when a test calls my main class, the dependencies don't get injected there. Here is my context (simplified version):
Login Class:
package net.openrally.restaurant.core.exposure.resource;
#Path("/login")
#Component
#Transactional
#Singleton
#Produces("application/json")
#Consumes("application/json")
public class Login extends BaseResource{
#Autowired
private UserDAO userDAO;
#POST
public Response post(String requestBody){
...
//NullPointerException
User user = userDAO.loadByCompanyIdAndLogin(companyId, login);
}
...
}
LoginTest Class:
package net.openrally.restaurant.core.exposure.resource;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/applicationContext.xml")
public class LoginTest extends BaseResourceTest {
#Autowired
private UserDAO userDAO;
...
#Test
public void testInvalidPassword() {
....
// Works perfectly!
userDAO.save(user);
....
}
}
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:configuration.properties</value>
</list>
</property>
</bean>
<context:annotation-config />
<context:component-scan base-package="net.openrally.restaurant.core" />
<import resource="db-config.xml" />
</beans>
I am searching for a solution for a few days now. From what I could find so far, most of the people who have #Autowired problems dont have either <context:annotation-config /> or xmlns:context="http://www.springframework.org/schema/context" in their spring xml or dont have a #Component family annotation in the class they want DI to take place, and as you can see, they are both there :(. I have only one applicationContext.xml in my project which suits for both runtime and test (I have distinct configuration.properties to set database credentials and log levels differently, but no spring configuration there)
I'm using:
Spring: 3.1.0.RELEASE
JUnit: 4.10
Jersey: 1.11
CLIB: 2.2.2
Any ideas, and I mean ANY :), is much appreciated.
UPDATE
The following logs come up when I run the test:
2012-03-27 07:37:02,457 DEBUG [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'login'
2012-03-27 07:37:02,457 DEBUG [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'login'
2012-03-27 07:37:02,459 DEBUG [main] org.springframework.beans.factory.annotation.InjectionMetadata - Found injected element on class [net.openrally.restaurant.core.exposure.resource.Login]: AutowiredFieldElement for private net.openrally.restaurant.core.persistence.dao.ConfigurationDAO net.openrally.restaurant.core.exposure.resource.Login.configurationDAO
2012-03-27 07:37:02,459 DEBUG [main] org.springframework.beans.factory.annotation.InjectionMetadata - Found injected element on class [net.openrally.restaurant.core.exposure.resource.Login]: AutowiredFieldElement for private net.openrally.restaurant.core.persistence.dao.UserDAO net.openrally.restaurant.core.exposure.resource.Login.userDAO
2012-03-27 07:37:02,459 DEBUG [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'login' to allow for resolving potential circular references
2012-03-27 07:37:02,459 TRACE [main] org.springframework.beans.CachedIntrospectionResults - Getting BeanInfo for class [net.openrally.restaurant.core.exposure.resource.Login]
2012-03-27 07:37:02,462 TRACE [main] org.springframework.beans.CachedIntrospectionResults - Caching PropertyDescriptors for class [net.openrally.restaurant.core.exposure.resource.Login]
2012-03-27 07:37:02,462 TRACE [main] org.springframework.beans.CachedIntrospectionResults - Found bean property 'class' of type [java.lang.Class]
2012-03-27 07:37:02,462 DEBUG [main] org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'login': AutowiredFieldElement for private net.openrally.restaurant.core.persistence.dao.ConfigurationDAO net.openrally.restaurant.core.exposure.resource.Login.configurationDAO
2012-03-27 07:37:02,462 DEBUG [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'configurationDAO'
2012-03-27 07:37:02,462 DEBUG [main] org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - Autowiring by type from bean name 'login' to bean named 'configurationDAO'
2012-03-27 07:37:02,463 DEBUG [main] org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'login': AutowiredFieldElement for private net.openrally.restaurant.core.persistence.dao.UserDAO net.openrally.restaurant.core.exposure.resource.Login.userDAO
2012-03-27 07:37:02,463 DEBUG [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'userDAO'
2012-03-27 07:37:02,463 DEBUG [main] org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - Autowiring by type from bean name 'login' to bean named 'userDAO'
2012-03-27 07:37:02,464 DEBUG [main] org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator - Creating implicit proxy for bean 'login' with 0 common interceptors and 1 specific interceptors
2012-03-27 07:37:02,464 DEBUG [main] org.springframework.aop.framework.Cglib2AopProxy - Creating CGLIB2 proxy: target source is SingletonTargetSource for target object [net.openrally.restaurant.core.exposure.resource.Login#60532a0a]
2012-03-27 07:37:02,465 DEBUG [main] org.springframework.aop.framework.Cglib2AopProxy - Unable to apply any optimisations to advised method: public javax.ws.rs.core.Response net.openrally.restaurant.core.exposure.resource.Login.post(java.lang.String)
Could Spring be creating my bean correctly but Jersey using its own non-autowired instance?
After researching a while, I could not find a way to make GrizzlyWeb use the context loaded by spring, so I tried to find an alternative solution.
I then found Hifaces20, which will let you start and stop a jetty instance, within the same JVM (which means you may, for instance, use a memory database that will be seen both by your tests and your application)
I had the exact same issue and later found that it was a developer issue :)
I was creating a new object instead of using the spring bean.
Lets say class MyService autowires a dao class MyDao myDaoBean. Now lets say I want to use MyService in MyController, I should wire in the Spring bean myServiceSpringBean. If I try to create a new myServiceObject then Spring doesn't wire the myDaoBean into the myServiceObject because it's not aware about that new service object.
And that leads to myDaoBean being null.

Resources