How I can fix this exception?
Without Spring Boot everything works.
So problem is in "App" section, am I right?
Caught exception
BeanCurrentlyInCreationException: Error creating bean with name 'pooledConnectionFactory':
Requested bean is currently in creation: Is there an unresolvable circular reference?
App
#ComponentScan
#EnableAutoConfiguration
#ImportResource("classpath:contexts/bean-locations.xml")
public class MyApp{
public static void main(String[] args) throws Exception {
new SpringApplication(MyApp.class).run(args);
}
}
Bean usage via import
<import resource="classpath*:contexts/database/datasource/base-data-source.xml"/>
<import resource="classpath*:contexts/database/datasource/pooled-data-source.xml"/>
First file from import:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<bean id="baseDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${connection.driverClassName}"/>
<property name="username" value="${connection.userName}"/>
<property name="password" value="${connection.password}"/>
<property name="url" value="${connection.url}"/>
</bean>
Second file from import:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<bean id="pool" class="org.apache.commons.pool.impl.GenericObjectPool">
<property name="minEvictableIdleTimeMillis"><value>300000</value></property>
<property name="timeBetweenEvictionRunsMillis"><value>60000</value></property>
</bean>
<bean id="dataSourceConnectionFactory" class="org.apache.commons.dbcp.DataSourceConnectionFactory">
<constructor-arg><ref bean="baseDataSource"/></constructor-arg>
</bean>
<bean id="pooledConnectionFactory" class="org.apache.commons.dbcp.PoolableConnectionFactory">
<constructor-arg index="0"><ref bean="dataSourceConnectionFactory"/></constructor-arg>
<constructor-arg index="1"><ref bean="pool"/></constructor-arg>
<constructor-arg index="2"><null/></constructor-arg>
<constructor-arg index="3"><null/></constructor-arg>
<constructor-arg index="4"><value>false</value></constructor-arg>
<constructor-arg index="5"><value>true</value></constructor-arg>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.PoolingDataSource"
depends-on="pooledConnectionFactory">
<constructor-arg><ref bean="pool"/></constructor-arg>
</bean>
Spring Boot has Database initialization feature which conflicts with your DataSource config. See DataSourceInitializer class. It tries to obtain data source before its creation.
To fix your app you can
Disable initializer using property
spring.datasource.initialize=false
Exclude data source auto config as you have your own configuration
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
Related
I have two datasources defined "datasource1" and "datasource2" (in xml configuration from a dependency).
Because of that I don't get JdbcTemplate configured by default so I need to do it manually, I do it like this:
1.
#Bean
public JdbcOperations jdbcOperations(DataSource datasource1) {
return new JdbcTemplate(datasource1);
}
2.
#Bean
public JdbcOperations jdbcOperations(#Qualifier("datasource1") DataSource datasource1) {
return new JdbcTemplate(datasource1);
}
In both cases it fails with:
Parameter 0 of method jdbcOperations in com.example.PersistentConfig required a single bean, but 2 were found:
- datasource1: defined in class path resource [datasources.xml]
- datasource2: defined in class path resource [datasources.xml]
Why the qualifier doesn't work?
I can't change the datasources.xml file to add a primary=true to datasource.
datasources.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="datasource1"
class="com.example.database.IdentifiedLazyConnectionDataSourceProxy">
<qualifier value="datasource1"/>
<property name="targetDataSource">
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/ak1Database"/>
<property name="resourceRef" value="true"/>
</bean>
</property>
<property name="identifier" value="shared"/>
</bean>
<bean id="datasource2"
class="com.example.database.IdentifiedLazyConnectionDataSourceProxy">
<qualifier value="datasource2"/>
<property name="targetDataSource">
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/ak2Database"/>
<property name="resourceRef" value="true"/>
</bean>
</property>
<property name="identifier" value="shared"/>
</bean>
</beans>
The reason this wasn't working is because xml configuration always overrides java config (see https://jira.spring.io/browse/SPR-7028).
To solve this I needed to create a bean that has different name then the one in the xml and mark that new bean as #Primary.
So now I will have three datasource beans, two connecting to the same database schema, but only one of the marked Primary so it will be used in default places instead of the xml defined one.
I have created a JUnit test in spring with next code:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {
"classpath:*/WEB-INF/demo-servlet.xml"})
public class CrudTestJUnit extends AbstractJUnit4SpringContextTests {
#Autowired
protected ShoppingCartDao shoppingCartDao;
#Autowired
private ApplicationContext context;
#Before
public void setUp(){
}
#Test
public void testSomething() {
System.out.println("Evo beanvoa:" + Arrays.toString(context.getBeanDefinitionNames()));
Assert.assertTrue(false);
}
}
In demo-servlet.xml i defined bean:
<bean id="shoppingCartDao" class="com.it355.hibernatecrud.dao.impl.ShoppingCartDaoImpl"></bean>
When i run JUnit test i get this error:
Error creating bean with name 'CrudTestJUnit': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected com.it355.hibernatecrud.dao.ShoppingCartDao CrudTestJUnit.shoppingCartDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.it355.hibernatecrud.dao.ShoppingCartDao] found for dependency:
When i delete shopping cart i get this from getBeanDefinitionNames():
Evo beanvoa:[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.event.internalEventListenerProcessor,
org.springframework.context.event.internalEventListenerFactory,
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor, org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]
Here is my full demo-servlet.xml file:
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--Kako bi Hibernate mogao da se poveže na bazu podataka potrebno je kreirati sesiju. To radimo u sledećem
zrnu-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" >
<!--Dodavanje path-a na kome se nalaze podešavanja za Hibernate -->
<value>classpath:hibernate.cfg.xml</value>
</property>
<!-- Dodavanje path-a paketa u kome se nalaze entity fajlovi na osnovu kojih
će Hibernate kreirati bazu i upisivati u nju-->
<property name="packagesToScan">
<list>
<value>com.it355.hibernatecrud.entity</value>
</list>
</property>
</bean>
<!--Transakcija se dešava između baze i programa korišćenjem Transaction Managera koji definišemo ovde
On koristi sesiju koju smo definisali iznad -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="shoppingCartDao" class="com.it355.hibernatecrud.dao.impl.ShoppingCartDaoImpl"></bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<context:component-scan base-package="com.it355.hibernatecrud" />
<mvc:annotation-driven conversion-service="conversionService" />
<tx:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/css/**" location="/WEB-INF/css/"/>
<mvc:resources mapping="/resources/**" location="/WEB-INF/" />
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.it355.hibernatecrud.converter.IntegerToCategory" />
</set>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
Am i wrong in calling configuration file or some other thing? Is there someone who had the same issue.
Also in my configuration file i have component scan configured and my application works and loads beans without any problem but JUnit is making a problem.
It seems that your XML configuration file can't be found or loaded properly, thus you aren't able to do the injections properly.
I suggest just use classpath, if your XML configuration file is within your CLASSPATH there's no need to mention WEB-INF etc'. Like this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:demo-servlet.xml")
public class CrudTestJUnit extends AbstractJUnit4SpringContextTests {
}
In the end i found out that Configuration from WEB-INF must be loaded like this:
#ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/demo-servlet.xml"})
I'm making my first steps in Spring. In my project I need to consume SOAP HTTPS web-service. I've a added JKSKeyManager bean to test config xml and ClassPathResource bean with certs. But when I run JUnit test I get
java.io.FileNotFoundException: class path resource [src/main/resources/cacerts] cannot be resolved to URL because it does not exist
but file is definitely in that directory.
Below is my config xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">`
<bean id="cucmsql" class="com.myname.myproject.CUCMDatabaseConnector" factory-method="getInstance">
<property name="marshaller" ref="marshaller"></property>
<property name="unmarshaller" ref="marshaller"></property>
<property name="properties" ref="properties"/>
</bean>
<bean id="properties" class="com.myname.myproject.SystemProperties" factory-method="getInstance">
</bean>
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="contextPath" value="com.cisco.axl" />
</bean>
<bean id="cacertsFile" class="org.springframework.core.io.ClassPathResource">
<constructor-arg value="src/main/resources/cacerts"/>
</bean>
<util:property-path id="cacertsUtil" path="cacertsFile.file"/>`
<bean id="keyManager" class="org.springframework.security.saml.key.JKSKeyManager">
<constructor-arg ref="cacertsUtil"></constructor-arg>
<constructor-arg>
<map>
<entry key="cucmpublisher" value="changeit"></entry>
<entry key="cucmsubcriber" value="changeit"></entry>
</map>
</constructor-arg>
<constructor-arg type="java.lang.String" value="changeit"></constructor-arg>
</bean>
</beans>
What am I doing wrong?
Judging by your project structure, you are probably using Maven, which means src/main/resources is a source folder.
As such, you need to change your configuration to:
<bean id="cacertsFile" class="org.springframework.core.io.ClassPathResource">
<constructor-arg value="/cacerts" />
</bean>
The path to a classpath resource is not relative to the project root but to the project source folders.
I have faced very strange issue with autowiring Hibernate SessionFactory bean into my Service.
I'm able to find SessionFactory bean in Spring Context object. So no issues with creating such bean.
But I can not autowire this bean into my service when it is marked with #Transactional annotation. Factory field is null.
Once I remove this annotation - everything works good.
Service Class:
#Service
#Transactional
public class ExampleRunner implements Runnable{
#Autowired
SessionFactory sessionFactory;
...
}
applicationContext.xml:
<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"
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">
<context:property-placeholder location="classpath:application.properties"
ignore-resource-not-found="true" />
<context:component-scan base-package="org.edu" />
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName:org.hsqldb.jdbcDriver}" />
<property name="url" value="${jdbc.url:jdbc:hsqldb:mem:myAppDb}" />
<property name="username" value="${jdbc.username:sa}" />
<property name="password" value="$jdbc.password:}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="org.edu" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
${hibernate.dialect:org.hibernate.dialect.HSQLDialect}
</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto:create-drop}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql:true}</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager"
proxy-target-class="true" />
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Usage:
public static void main(String[] args) {
Runnable runner = new ClassPathXmlApplicationContext("applicationContext.xml").getBean(ExampleRunner.class);
runner.run();
}
Seems like when I make #Transactional as class level annotation Spring creates CGLib proxy bean where SessionFactory field is null.
But when I use #Transational as method level annotation everything works good.
So I just want to understand such behavior.
What have I missed from Spring documentation?
I use Spring 4.1.4.RELEASE.
I got your error actually why you getting problem here because you not allowing container to auto-wired bean for you as you using java Main method it will not auto-wired bean that's why you getting error.
I am trying to put some initialization methods in controller's default constructor, but the problem that it never called. When I put an #Autowired annotation, the error is throuwn - Autowired annotation requires at least on argument.
What the best practice for putting some initialization code in one place except of putting it in each controller's method?
Thank you
#InitBinder
public void initBinder(WebDataBinder binder) {
try {
initialize();
Logger l = Logger.getLogger(this.getClass().getName());
l.warning("Init!!!");
} catch (Exception e) {
e.printStackTrace();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="de.butler.crm.controller" />
<mvc:annotation-driven />
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="l" />
</bean>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="de.butler.crm.resource.Resources" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="de" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="50000000"/>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
a) Controllers are just plain Spring Beans, so that all aspects of the Spring Bean lifecycle apply.
I.e. you can autowire properties or constructor parameters (with annotation support), you can initialize beans using the InitializingBean interface or a #PostConstruct method etc.
If none of this works, then there's something wrong with your setup and you'll have to post your web context xml and / or a stack trace.
b) If you need a per-request setup, then use the #InitBinder mechanism
By default life cycle of bean in spring is managed by Spring container .If you want to initialized your bean with some of your code you can do it with #postconstruct method.
You have to create listener for your bean and whenever your bean is initialized this two method will invoke #postconstruct and #predestroy so you have to use this method for doing things