Announcement Announcement Module
Collapse

JavaConfig forum decommissioned in favor of Core Container

As described at

http://static.springsource.org/sprin...fig/README.TXT

key features of the Spring JavaConfig project have been migrated into the core Spring Framework as of version 3.0.

Please see the Spring 3.0 documentation on @Configuration and @Bean support:

http://static.springsource.org/sprin...tml#beans-java

For any questions related to @Configuration classes and @Bean methods in Spring 3.0, please post in the dedicated 'Core Container' forum at

http://forum.springsource.org/forumdisplay.php?f=26
See more
See less
Could not register object Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Could not register object

    Hi

    Could someone please explain to me what could cause this exception?

    Code:
    Caused by: java.lang.IllegalStateException: Could not register object [[email protected]8] under bean name 'dataSource': there is already object [[email protected]2] bound
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.registerSingleton(DefaultSingletonBeanRegistry.java:124)
    	at org.springframework.config.java.internal.factory.DefaultJavaConfigBeanFactory.registerSingleton(DefaultJavaConfigBeanFactory.java:108)
    	at org.springframework.config.java.internal.enhancement.CglibConfigurationEnhancer$BeanMethodInterceptor.doIntercept(CglibConfigurationEnhancer.java:338)
    	at org.springframework.config.java.internal.enhancement.CglibConfigurationEnhancer$AbstractMethodInterceptor.intercept(CglibConfigurationEnhancer.java:215)
    	at com.xxx.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905.dataSource(<generated>)
    	at com.xxx.configuration.DataAccessContext.sessionFactory(DataAccessContext.java:121)
    	at com.xxx.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905.CGLIB$sessionFactory$10(<generated>)
    	at com.xxx.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905$$FastClassByCGLIB$$d4ac3b7a.invoke(<generated>)
    	at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:167)
    	at org.springframework.config.java.internal.enhancement.CglibConfigurationEnhancer$BeanMethodInterceptor.doIntercept(CglibConfigurationEnhancer.java:328)
    	at org.springframework.config.java.internal.enhancement.CglibConfigurationEnhancer$AbstractMethodInterceptor.intercept(CglibConfigurationEnhancer.java:215)
    	at com.xxx.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905.sessionFactory(<generated>)
    	at com.xxx.configuration.DataAccessContext.transactionManager(DataAccessContext.java:141)
    	at com.xxx.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905.CGLIB$transactionManager$8(<generated>)
    	at com.xxx.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905$$FastClassByCGLIB$$d4ac3b7a.invoke(<generated>)
    	at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:167)
    	at org.springframework.config.java.internal.enhancement.CglibConfigurationEnhancer$BeanMethodInterceptor.doIntercept(CglibConfigurationEnhancer.java:328)
    	at org.springframework.config.java.internal.enhancement.CglibConfigurationEnhancer$AbstractMethodInterceptor.intercept(CglibConfigurationEnhancer.java:215)
    	at com.xxx.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905.transactionManager(<generated>)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    	at java.lang.reflect.Method.invoke(Method.java:597)
    	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:115)
    	... 140 more
    Last edited by mah01; Oct 22nd, 2009, 07:16 AM.

  • #2
    I guess that maybe itīs not that easy to figure out from just the exception stacktrace since there are no answers

    Lets see if I can add some more information that might make it easier to understand the problem.

    This is part of my config (Spring JavaConfig):

    Code:
    @Configuration
    @AnnotationDrivenConfig
    public class DataAccessContext extends ConfigurationSupport
    {
    
    	@Bean
    	public DataSource dataSource() // NO_UCD
    	{
    		DriverManagerDataSource dataSource = new DriverManagerDataSource(url(), username(), password());
    		dataSource.setDriverClassName(driverClassName());
    		return dataSource;
    	}
    	
    	@Bean
    	public SessionFactory sessionFactory() // NO_UCD
    	{
    		AnnotationSessionFactoryBean factoryBean = new AnnotationSessionFactoryBean();
    
    		factoryBean.setDataSource(dataSource());
    
    		Class[] annotatedClasses = new Class[] {
    				PaymentPlanMapping.class,
    				BatchFileSequence.class };
    		factoryBean.setAnnotatedClasses(annotatedClasses);
    
    		Properties hibernateProperties = new Properties();
    		hibernateProperties.put("hibernate.dialect", databaseDialect());
    		hibernateProperties.put("hibernate.default_schema", databaseSchema());
    		hibernateProperties.put("hibernate.cache.provider_class", EhCacheProvider.class);
    		hibernateProperties.put("hibernate.cache.use_second_level_cache", true);
    		factoryBean.setHibernateProperties(hibernateProperties);
    
    		return this.getObject(factoryBean, SessionFactory.class);
    	}
    It works just fine. But now I want transactional support so I add a transaction manager bean and the @AnnotationDrivenTx annotation. The config now looks like this (added stuff in bold face):

    Code:
    @Configuration
    @AnnotationDrivenConfig
    @AnnotationDrivenTx(transactionManager = "transactionManager")
    public class DataAccessContext extends ConfigurationSupport
    {	
    
    	@Bean
    	public DataSource dataSource() // NO_UCD
    	{
    		DriverManagerDataSource dataSource = new DriverManagerDataSource(url(), username(), password());
    		dataSource.setDriverClassName(driverClassName());
    		return dataSource;
    	}
    	
    	@Bean
    	public SessionFactory sessionFactory() // NO_UCD
    	{
    		AnnotationSessionFactoryBean factoryBean = new AnnotationSessionFactoryBean();
    
    		factoryBean.setDataSource(dataSource());
    
    		Class[] annotatedClasses = new Class[] {
    				PaymentPlanMapping.class,
    				BatchFileSequence.class };
    		factoryBean.setAnnotatedClasses(annotatedClasses);
    
    		Properties hibernateProperties = new Properties();
    		hibernateProperties.put("hibernate.dialect", databaseDialect());
    		hibernateProperties.put("hibernate.default_schema", databaseSchema());
    		hibernateProperties.put("hibernate.cache.provider_class", EhCacheProvider.class);
    		hibernateProperties.put("hibernate.cache.use_second_level_cache", true);
    		factoryBean.setHibernateProperties(hibernateProperties);
    
    		return this.getObject(factoryBean, SessionFactory.class);
    	}
    
    	@Bean
    	public HibernateTransactionManager transactionManager() // NO_UCD
    	{
    		return new HibernateTransactionManager(sessionFactory());
    	}
    The addition of these two things makes the exception below appear. Any ideas?

    Code:
    Caused by: java.lang.IllegalStateException: Could not register object [sa] under bean name 'username': there is already object [sa] bound
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.registerSingleton(DefaultSingletonBeanRegistry.java:124)
    	at org.springframework.config.java.internal.factory.DefaultJavaConfigBeanFactory.registerSingleton(DefaultJavaConfigBeanFactory.java:108)
    	at org.springframework.config.java.internal.enhancement.CglibConfigurationEnhancer$BeanMethodInterceptor.doIntercept(CglibConfigurationEnhancer.java:338)
    	at org.springframework.config.java.internal.enhancement.CglibConfigurationEnhancer$AbstractMethodInterceptor.intercept(CglibConfigurationEnhancer.java:215)
    	at com.xxx.yyy.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905.username(<generated>)
    	at com.xxx.yyy.configuration.DataAccessContext.dataSource(DataAccessContext.java:112)
    	at com.xxx.yyy.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905.CGLIB$dataSource$8(<generated>)
    	at com.xxx.yyy.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905$$FastClassByCGLIB$$d4ac3b7a.invoke(<generated>)
    	at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:167)
    	at org.springframework.config.java.internal.enhancement.CglibConfigurationEnhancer$BeanMethodInterceptor.doIntercept(CglibConfigurationEnhancer.java:328)
    	at org.springframework.config.java.internal.enhancement.CglibConfigurationEnhancer$AbstractMethodInterceptor.intercept(CglibConfigurationEnhancer.java:215)
    	at com.xxx.yyy.configuration.DataAccessTestContext$$EnhancerByCGLIB$$2cc1b905.dataSource(<generated>)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    	at java.lang.reflect.Method.invoke(Method.java:597)
    	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:115)
    	... 139 more
    Itīs as if Spring JavaConfig is trying to create a singleton bean twice...
    Last edited by mah01; Oct 22nd, 2009, 07:34 AM.

    Comment


    • #3
      I noticed a copule of interesting things in the log. Maybe you guys understand what it means?

      Look at the bold parts, it seems like the url bean is created twice (failing on the second attempt)

      Code:
      ...
      ...
      INFO  DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@118278a: defining beans [com.xxx.yyy.configuration.DataAccessTestContext,com.xxx.yyy.configuration.JmsTestContext,com.xxx.yyy.configuration.ApplicationTestContext,com.xxx.yyy.configuration.MailTestContext,url,databaseDialect,transactionManager,databaseSchema,dataSource,paymentPlanCodeDao,sessionFactory,driverClassName,password,configuration,batchFileSequenceDao,username,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.config.internalTransactionAdvisor,statusMessageQueue,chargebackMessageQueue,batchOrderQueue,jmsTemplate,batchOrderQueueName,jmsConnectionFactory,listener,container,chargebackMessageQueueName,txUpdateMessageQueue,txUpdateMessageQueueName,messageIdEnabled,hostIp,statusMessageQueueName,jmsConnectionFactoryInitialiser,reconcileSleepTime,reconcileRegex,batchService,chargebackManager,cryptoManager,reconcileManager,loggingAdviceProxyCreator,batchUploadFilename,chargebackRegex,shredFilenamePattern,loggingAdvice,txUpdateClient,reconcileDir,reportFileService,chargebackClient,batchFileBuilder,dbService,batchCrypto,batchFileService,batchManager,jmsStatusClient,batchOutputDir,shredOlderThan,chargebackSleepTime,shredRemove,jmsService,chargebackDir,clock,mailSmtpHost,mailMessageFactory,mailFrom,mailSender,mailService,mailToAlert]; root of factory hierarchy
      DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean 'com.xxx.yyy.configuration.DataAccessTest
      ...
      ...
      DEBUG DefaultListableBeanFactory - Creating shared instance of singleton bean 'url'
      DEBUG DefaultListableBeanFactory - Creating instance of bean 'url'
      DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean 'com.xxx.yyy.configuration.DataAccessTestContext'
      INFO  CglibConfigurationEnhancer$BeanMethodInterceptor - Registering new PUBLIC singleton object [jdbc:hsqldb:mem:YYY] for @Bean method DataAccessTestContext.url
      DEBUG DefaultListableBeanFactory - Eagerly caching bean 'url' to allow for resolving potential circular references
      DEBUG CachedIntrospectionResults - Getting BeanInfo for class [java.lang.String]
      DEBUG CachedIntrospectionResults - Caching PropertyDescriptors for class [java.lang.String]
      DEBUG CachedIntrospectionResults - Found bean property 'bytes' of type [[B]
      DEBUG CachedIntrospectionResults - Found bean property 'class' of type [java.lang.Class]
      DEBUG CachedIntrospectionResults - Found bean property 'empty' of type [boolean]
      DEBUG CachedIntrospectionResults - Not strongly caching class [java.lang.String] because it is not cache-safe
      DEBUG DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
      DEBUG DefaultListableBeanFactory - Creating instance of bean 'org.springframework.transaction.config.internalTransactionAdvisor'
      DEBUG InfrastructureAdvisorAutoProxyCreator - Did not attempt to auto-proxy infrastructure class [org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor]
      DEBUG BeanNameAutoProxyCreator - Did not attempt to auto-proxy infrastructure class [org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor]
      DEBUG DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.transaction.config.internalTransactionAdvisor' to allow for resolving potential circular references
      DEBUG CachedIntrospectionResults - Getting BeanInfo for class [org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor]
      DEBUG CachedIntrospectionResults - Caching PropertyDescriptors for class [org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor]
      DEBUG CachedIntrospectionResults - Found bean property 'advice' of type [org.aopalliance.aop.Advice]
      DEBUG CachedIntrospectionResults - Found bean property 'class' of type [java.lang.Class]
      DEBUG CachedIntrospectionResults - Found bean property 'classFilter' of type [org.springframework.aop.ClassFilter]
      DEBUG CachedIntrospectionResults - Found bean property 'order' of type [int]
      DEBUG CachedIntrospectionResults - Found bean property 'perInstance' of type [boolean]
      DEBUG CachedIntrospectionResults - Found bean property 'pointcut' of type [org.springframework.aop.Pointcut]
      DEBUG CachedIntrospectionResults - Found bean property 'transactionInterceptor' of type [org.springframework.transaction.interceptor.TransactionInterceptor]
      DEBUG DefaultListableBeanFactory - Creating instance of bean '(inner bean)'
      DEBUG InfrastructureAdvisorAutoProxyCreator - Did not attempt to auto-proxy infrastructure class [org.springframework.transaction.interceptor.TransactionInterceptor]
      DEBUG BeanNameAutoProxyCreator - Did not attempt to auto-proxy infrastructure class [org.springframework.transaction.interceptor.TransactionInterceptor]
      DEBUG CachedIntrospectionResults - Getting BeanInfo for class [org.springframework.transaction.interceptor.TransactionInterceptor]
      DEBUG CachedIntrospectionResults - Caching PropertyDescriptors for class [org.springframework.transaction.interceptor.TransactionInterceptor]
      DEBUG CachedIntrospectionResults - Found bean property 'class' of type [java.lang.Class]
      DEBUG CachedIntrospectionResults - Found bean property 'transactionAttributeSource' of type [org.springframework.transaction.interceptor.TransactionAttributeSource]
      DEBUG CachedIntrospectionResults - Found bean property 'transactionAttributeSources' of type [[Lorg.springframework.transaction.interceptor.TransactionAttributeSource;]
      DEBUG CachedIntrospectionResults - Found bean property 'transactionAttributes' of type [java.util.Properties]
      DEBUG CachedIntrospectionResults - Found bean property 'transactionManager' of type [org.springframework.transaction.PlatformTransactionManager]
      DEBUG DefaultListableBeanFactory - Creating shared instance of singleton bean 'transactionManager'
      DEBUG DefaultListableBeanFactory - Creating instance of bean 'transactionManager'
      DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean 'com.xxx.yyy.configuration.DataAccessTestContext'
      DEBUG DefaultListableBeanFactory - Creating shared instance of singleton bean 'sessionFactory'
      DEBUG DefaultListableBeanFactory - Creating instance of bean 'sessionFactory'
      DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean 'com.xxx.yyy.configuration.DataAccessTestContext'
      SLF4J: This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version
      DEBUG DefaultListableBeanFactory - Creating shared instance of singleton bean 'dataSource'
      DEBUG DefaultListableBeanFactory - Creating instance of bean 'dataSource'
      DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean 'com.xxx.yyy.configuration.DataAccessTestContext'
      INFO  CglibConfigurationEnhancer$BeanMethodInterceptor - Registering new PUBLIC singleton object [jdbc:hsqldb:mem:YYY] for @Bean method DataAccessTestContext.url
      INFO  DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@118278a: defining beans [com.xxx.yyy.configuration.DataAccessTestContext,com.xxx.yyy.configuration.JmsTestContext,com.xxx.yyy.configuration.ApplicationTestContext,com.xxx.yyy.configuration.MailTestContext,url,databaseDialect,transactionManager,databaseSchema,dataSource,paymentPlanCodeDao,sessionFactory,driverClassName,password,configuration,batchFileSequenceDao,username,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.config.internalTransactionAdvisor,statusMessageQueue,chargebackMessageQueue,batchOrderQueue,jmsTemplate,batchOrderQueueName,jmsConnectionFactory,listener,container,chargebackMessageQueueName,txUpdateMessageQueue,txUpdateMessageQueueName,messageIdEnabled,hostIp,statusMessageQueueName,jmsConnectionFactoryInitialiser,reconcileSleepTime,reconcileRegex,batchService,chargebackManager,cryptoManager,reconcileManager,loggingAdviceProxyCreator,batchUploadFilename,chargebackRegex,shredFilenamePattern,loggingAdvice,txUpdateClient,reconcileDir,reportFileService,chargebackClient,batchFileBuilder,dbService,batchCrypto,batchFileService,batchManager,jmsStatusClient,batchOutputDir,shredOlderThan,chargebackSleepTime,shredRemove,jmsService,chargebackDir,clock,mailSmtpHost,mailMessageFactory,mailFrom,mailSender,mailService,mailToAlert]; root of factory hierarchy
      DEBUG DefaultListableBeanFactory - Retrieved dependent beans for bean 'com.xxx.yyy.configuration.ApplicationTestContext': [com.xxx.yyy.configuration.JmsTestContext]
      DEBUG DefaultListableBeanFactory - Retrieved dependent beans for bean 'com.xxx.yyy.configuration.JmsTestContext': [com.xxx.yyy.configuration.ApplicationTestContext]
      Last edited by mah01; Oct 22nd, 2009, 07:41 AM.

      Comment


      • #4
        Hi

        I don't understand what the problem was but I managed to solve it.

        I didn't show you guys the part of my config where I got the url, username etc.

        This is from DataAccessContext.java:

        Code:
        @Bean
        public String username()
        {
        	String property = getConfiguredProperty("jdbc.username");
        	ConfigUtil.assertProperty(property, "jdbc.username");
        	return property;
        }
        That method is overridden in DataAccessTestContext.java:
        Code:
        @Bean
        @Override
        public String username()
        {
        	return "sa";
        }
        I will make sure that the DataAccessTestContext.java is loaded if I'm running a JUnit-test and DataAccessContext.java in production.

        That way, when for example the data source bean is created it will use either production or test configuration depending on which context file is loaded.

        Code:
        @Bean
        public DataSource dataSource() // NO_UCD
        {
        	// url, username etc. comes url() in this class (DataAccessContext.java) or from the subclass (DataAccessTestContext.java
        	DriverManagerDataSource dataSource = new DriverManagerDataSource(url(), username(), password());
        	dataSource.setDriverClassName(driverClassName());
        	return dataSource;
        }
        By removing the @Bean annotations from the "configuration data" methods (i.e. url(), username() etc), I got rid of the exception. I don't know why though. Do any of you know?

        Changed DataAccessContext.java:

        Code:
        public String username()
        {
        	String property = getConfiguredProperty("jdbc.username");
        	ConfigUtil.assertProperty(property, "jdbc.username");
        	return property;
        }
        Changed DataAccessTestContext.java:
        Code:
        @Override
        public String username()
        {
        	return "sa";
        }

        Comment

        Working...
        X