spring multiple property file - spring

I have a spring project. There are two property files. one property file is config in dbConfig.xml and I cannot change it. I have my own appConfig.xml
I have the following in it
<util:properties id="configProps" location="classpath:spring/config.properties" />
<bean id="createDummyDataTask" class="com.merc.spring.CreateDummyData" scope="step">
<property name="srcFolder" value="${configProps.srcDir}"/>
</bean>
using either srcDir or configProps.srcDir does not seem to work.

${} works only for property files loaded by the context:propertyplaceholder. If you are using spring 3.0 you can use #{} which is processed as a Spel (spring expression language). The following should work.
<util:properties id="configProps" location="classpath:spring/config.properties" />
<bean id="createDummyDataTask" class="com.merc.spring.CreateDummyData" scope="step">
<property name="srcFolder" value="#{configProps.srcDir}"/>
</bean>

Here how we resolved it
Context.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="Settings.xml"/>
<import resource="Database.xml"/>
</beans>
Settings.xml
In the list many property file could be added
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>db.properties</value>
</list>
</property>
</bean>
</beans>
Sample bean for processing db.properties file
Database.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!-- the transaction manager -->
<bean id="dstxnManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="appDataSource"/>
</bean>
<!-- the DataSource (parameterized for configuration via a PropertyPlaceHolderConfigurer) -->
<bean id="appDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" lazy-init="false">
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${jdbcUrl}" />
<property name="user" value="${username}" />
<property name="password" value="${password}" />
</bean>
<!-- DB connection factory -->
<bean id="storageDaoFactory" class="com.dao.StorageDAOFactory">
<constructor-arg><ref bean="dstxnManager"/></constructor-arg>
</bean>
</beans>

Related

Spring & Hibernate - Error when using #Transactional

I have an application setup based on a previous configuration - which was 100% functional. Now I am using maven and am encountering an Error in my controller class which says i must configure Beans.xml.
I'm not sure exactly what this means, as I have my dispatcher-servlet.xml configured in the same way as the functional application.
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<context:component-scan base-package="com.me.test.controller"/>
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="url" value="jdbc:derby://localhost:1527/userDB"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userDao" class="com.me.test.dao.UserDAOImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
Edit: Screenshot of error. Which occurs when using the #Transactional annotation.

Does lazy-init actually work as advertised?

According to the documentation http://docs.spring.io/spring-framework/docs/3.2.2.RELEASE/spring-framework-reference/html/beans.html#beans-factory-lazy-init the below should not be instatiating MyDatabase yet I can clearly see this is the case in the afterPropertiesSet method of the HibernateDatabase class when debugging. If I remove MyDatabaseEntityManagerFactory then this does not occur. However this should not matter given that MyDatabaseEntityManagerFactory is also lazy - it should not cause MyDatabase to initialise.
Either I'm misunderstanding the part of the docs that say that a lazy bean referencing another lazy bean shouldn't cause it to initialise or there is a fundamental problem in Spring here. Can anyone shed some light on this or possibly suggest an alternative to what I want to achieve?
Thanks.
<?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: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-3.0.xsd"
default-lazy-init="false">
<bean id="HibernateDatabase" class="mypackage.database.HibernateDatabase"
abstract="true" />
<bean id="MyDatabase" parent="HibernateDatabase" lazy-init="true">
<property name="driver" value="com.sybase.jdbc3.jdbc.SybDriver" />
<property name="dialect" value="org.hibernate.dialect.SybaseDialect" />
<property name="url" value="${My.dburl}" />
<property name="user" value="${My.dbuser}" />
<property name="password" value="${My.dbpassword}" />
</bean>
<bean id="EntityManagerFactory" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
abstract="true">
<property name="targetMethod" value="getEntityManagerFactory" />
</bean>
<bean id="MyDatabaseEntityManagerFactory" parent="EntityManagerFactory" lazy-init="true">
<property name="targetObject" ref="MyDatabase" />
</bean>
</beans>

How to configure Hibernate when you are using a Spring Session Factory

I am trying to setup Hibernate Tools in eclipse. The trouble is that it can't find any mapping files.
I have created a console configuration that points to my environment.properties file and hibernate.cfg.xml. The trouble is that there are no mappings in hibernate.cfg.xml.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
</session-factory>
</hibernate-configuration>
it seems that it is using the spring bean sessionFactory in myproject-persistence.xml (below) to find the required mapping files. I can't see anywhere that this file can be added to the the Console Configuration in eclipse.
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${hibernate.connection.driver_class}" />
<property name="jdbcUrl" value="${hibernate.connection.url}" />
<property name="user" value="${hibernate.connection.username}" />
<property name="password" value="${hibernate.connection.password}" />
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="25" />
<property name="acquireIncrement" value="5" />
<property name="maxIdleTime" value="1800" />
<property name="numHelperThreads" value="5" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
</props>
</property>
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="mappingLocations">
<list><value>classpath*:com/mybusiness/myproject/platform/api/**/*.hbm.xml</value></list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
</beans>
How can I get this working?
UPDATE
I managed to get a single Mapping working by adding it to the 'Mappings' tab in 'Edit Configuration'. However, I can't use wildcards here and would have to add every mapping manually.
Hibernate Tools is not available under Hibernate 4.x version. It is available with version 3.2. If you are using maven, the dependency goes as:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.4.GA</version>
<scope>runtime</scope>
</dependency>
Now, the hibernate configuration for the tools got nothing to do with spring. An example xml will be (values in this example is for sql server):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="reversengineeringfactory">
<property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:jtds:sqlserver://myinstance:port/mydb</property>
<property name="hibernate.connection.username">dbuser</property>
<property name="hibernate.connection.password">dbpass</property>
<property name="hibernate.default_catalog">mydb</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
</session-factory>
</hibernate-configuration>
Now, For configuring the hibernate config xml in eclipse, you should choose Hibernate Perspective --> Edit Configuration --> Go for configuration File Setup.
A sample reverse engineering xml is below (gives granular control over code generation)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >
<hibernate-reverse-engineering>
<table-filter match-schema="dbo" match-name="Employee"
package="com.maggu.domain.model" />
<table-filter match-schema="dbo" match-name="Company"
package="com.maggu.domain.model" />
<table schema="dbo" name="Employee">
<primary-key>
<generator class="identity" />
</primary-key>
</table>
<table schema="dbo" name="Company">
<primary-key>
<generator class="identity" />
</primary-key>
</table>
</hibernate-reverse-engineering>
HTH
if you are using annotations to create your persistence entities than you can do like:
<bean id = "mySessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name = "packagesToScan">
<list>
<value>entityclasses</value>
</list>
</property>
where entityclasses is the package which contains all your entity classes. Let me know if it helps!!

Spring 3 with Thymeleaf config issue

Hello I have the following jars in my build path -
spring-beans-3.1.2.RELEASE.jar
spring-context-3.1.2.RELEASE.jar
spring-core-3.1.2.RELEASE.jar
spring-expression-3.1.2.RELEASE.jar
spring-web-3.1.2.RELEASE.jar
spring-webmvc-3.1.2.RELEASE.jar
thymeleaf-spring3-2.0.13.jar
and my servlet
<?xml version="1.0" encoding="UTF-8"?><br>
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="web.controller" />
<!-- Enabling Spring MVC configuration through annotations -->
<mvc:annotation-driven />
<!-- Mapping Static Resources -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="order" value="1" />
<property name="viewNames" value="*.html" />
</bean>
</beans>
The error I get on launching is -
Cannot find class [org.thymeleaf.templateresolver.ServletContextTemplateResolver] for bean with name 'templateResolver' defined in ServletContext resource [/WEB-INF/springMVC-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.thymeleaf.templateresolver.ServletContextTemplateResolver
Am I missing any other library here? Any help is much appreciated.
You are missing the actual Thymeleaf jar. You included the Spring jar that provides the integration but you missed the actual implementation of it.
Download the jar from here
thymeleaf download site

PersistenceAnnotationBeanPostProcessor vs JpaVendorAdapter

I'm setting up a maven-spring-hibernate-mysql-tomcat environment.
I would like to inject my Entity manager using the #PersistenceContext annotation.
As I understand to do this, I should have PersistenceAnnotationBeanPostProcessor defined in my application context, pointing to my persistence.xml file.
In this case my application context could be looking like this more or less:
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task" xmlns:ox="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-3.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- Context -->
<context:component-scan base-package="com.yl.mypack" />
<!-- AOP -->
<aop:aspectj-autoproxy />
<!-- Properties -->
<context:property-placeholder
location="classpath:db.connection.properties,applicationProperties.properties" />
<!-- DB Connection Pool -->
<bean id="dataSourceGlobal" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<!-- Data Source -->
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${jdbcUrl}" />
<property name="user" value="${user}" />
<property name="password" value="${password}" />
<!-- C3P0 Connection pool properties -->
<property name="minPoolSize" value="${c3p0.min_pool_size}" />
<property name="maxPoolSize" value="${c3p0.max_pool_size}" />
<property name="unreturnedConnectionTimeout" value="${c3p0.timeout}" />
<property name="idleConnectionTestPeriod" value="${c3p0.idle_test_period}" />
<property name="maxStatements" value="${c3p0.max_statements}" />
<property name="automaticTestTable" value="${c3p0.automatic_test_table}" />
</bean>
<!-- JPA -->
<!-- Creates a EntityManagerFactory for use with the Hibernate JPA provider -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
<property name="persistenceUnitName" value="myPU" />
<property name="dataSource" ref="dataSourceGlobal" />
</bean>
<!-- In order to enable EntityManager injection -->
<bean id="persistenceAnnotation"
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="persistenceUnits">
<map>
<entry key="myPU" value="classpath:META-INF/persistence.xml" />
</map>
</property>
</bean>
<!-- Transactions -->
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSourceGlobal" />
</bean>
</beans>
My persistence.xml could look like this:
<persistence-unit name="myPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.transaction.flush_before_completion"
value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
So now I guess I should be able to inject my entity manager using the #PersistenceContext annotation, at list this is what I get from the documentation. Before I'mm getting to JpaVendorAdapter, my first question would refer the entity manager factory definition:
The following properties:
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
<property name="persistenceUnitName" value="myPU" />
Are these required to be referred from the entity manager factory? Is it a must?
My second question would be regarding the JpaVendorAdapter, and in my case HibernateJpaVendorAdapter.
If I use HibernateJpaVendorAdapter, do I still need to have a persistence.xml file? Since some of the properties are overlapping. Moreover, do I still need to have PersistenceAnnotationBeanPostProcessor defined, pointing to my persistence.xml file? Can these 2 go together (PersistenceAnnotationBeanPostProcessor and HibernateJpaVendorAdapter)? Should they go together? What is the best practice, assuming I'm avoiding any JDNI style definitions?
Thanks in advance
The combination of data source bean and HibernateJpaVendorAdapter allows you to get rid of persistence.xml with Spring 3.1. Check out this article:
http://www.baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/
So the answers:
They are not a must.
No, you don't need to have a persistence.xml.
I am not exactly sure of what use PersistenceAnnotationBeanPostProcessor is.
<context:component-scan base-package="com.demo.dao" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="hibernate-resourceLocal"/>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
My Spring application context xml looks as simple as this. And it is working.
I don't what the best practice is, but I will keep persistence.xml so that in case I need to expose my service as session bean, it can be easily done.

Resources