Wednesday, June 18, 2008

Spring basic examples

EXAMPLES USING Spring's ApplicationContext class gives support for application framework services.

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class PersonTest
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
//ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
//ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
PersonHelper personHelper = (PersonHelper) context.getBean("PersonHelper");
List personList = (List)personHelper.getPersonList();
}

}

public class PersonHelper extends HibernateDaoSupport implements DatabaseHelperInterface
{
public List getPersonList() throws PersonDAOException
{
Session session = SessionFactoryUtils.getSession(this.getSessionFactory(), false);
List personList = new ArrayList();
try {
Query query = session.createQuery("from com.test.Person as person order by perosn.personName");
Iterator it = query.iterate();
while (it.hasNext()) {
Person person = (Person) it.next();
personList.add(person);
}
return personList;
}
catch (HibernateException ex)
{
throw new PersonDAOException("getPersonList(): " + ex.getMessage());
}
finally
{
try
{
session.close();
}
catch (HibernateException ex)
{
logger.fatal(ex);
}
}

}
}

import net.sf.hibernate.SessionFactory;


public interface DatabaseHelperInterface {
public SessionFactory getSessionFactory();

public void setSessionFactory(SessionFactory sessionFactory);
}

In applicationContext.xml

<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>com/onerail/orion/common/hibernate/bean/Person.hbm.xml</value>
<value>com/onerail/orion/common/hibernate/bean/PersonRoles.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.username">${hibernate.connection.username}</prop>
<prop key="hibernate.connection.password">${hibernate.connection.password}</prop>
<prop key="hibernate.connection.url">${hibernate.connection.url}</prop>
<prop key="hibernate.dialect">net.sf.hibernate.dialect.InformixDialect</prop>
<prop key="hibernate.connection.driver_class">${hibernate.connection.driver_class}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.use_outer_join">true</prop>
<prop key="hibernate.transaction.factory_class">net.sf.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.dbcp.minIdle">1</prop>
<!-- <prop key="hibernate.cache.use_query_cache">true</prop> -->
<!-- <prop key="hibernate.connection.pool_size">3</prop> -->
<!-- <prop key="hibernate.cache.provider_class">com.onerail.orion.common.hibernate.patch.OSCacheProvider</prop> -->
<prop key="hibernate.cglib.use_reflection_optimizer">false</prop>

<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>

</props>
</property>
</bean>

<!-- placeholderConfig loads extra configuration information which is placed into the expressions eg ${com.test.util.constants.dbUser} -->
<bean id="placeholderConfig"
class="com.onerail.orion.common.hibernate.config.HibernateProperties">
<property name="location"><value>classpath:config/runtime.properties</value></property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>

<!-- Spring AOP interceptor used to manage sessions -->
<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>

<bean id="hibernateDaoSupport" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.onerail.orion.reservation.nontravelproducts.DatabaseHelperInterface,com.onerail.orion.reservation.nontravelftr.DatabaseHelperInterface2</value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>

<!-- To set properties that reference other beans <ref>, subelement of <property> is used as shown below -->

<bean id="PersonHelper" class="com.test.PersonHelper" scope="prototype">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
</beans>




In web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


package com.onerail.orion.common.hibernate.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.Properties;

public class HibernateProperties extends PropertyPlaceholderConfigurer
implements InitializingBean {
private static Logger logger = SystemLog.getLogger(HibernateProperties.class);

private static boolean started = false;

private static Properties prop = new Properties();

protected String resolvePlaceholder(String s, Properties properties) {
if (started == false) {
synchronized (prop) {
if (started == false)
{
Constants.purge();
prop.setProperty("hibernate.connection.username", Constants.getDbUser());
prop.setProperty("hibernate.connection.password", Constants.getDbPassword());
prop.setProperty("hibernate.connection.url", Constants.getDatabaseUrl());
prop.setProperty("hibernate.connection.driver_class", Constants.getDbDrivers());
started = true;
}
}
}
if (prop.get(s) != null)
return (String) prop.get(s);
return super.resolvePlaceholder(s, properties);
}


public void afterPropertiesSet() throws Exception {
}
}


EXAMPLES USING Spring's BeanFactory class gives configuration framework and basic functionality (bean managing)

public interface PersonIF
{
public String getPersonAddress(String name);
}


public class PersonImpl implements PersonIF

{
private String address;
private int age;
private PersonRole personRole;

public PersonImpl(int myAge)
{
this.age = myAge;
}

public PersonImpl(PersonRole personRole)
{
this.personRole = personRole;
}


public String getAddress(String name)
{
return DatabaseHelper.getAddress(name);
}

public void setAddress(String myAddress)

{
this.address = myAddress;
}

public String getPersonRole(String name)
{
return DatabaseHelper.getRoles(name);
}

public void setPersonRoles(String role)

{
this.role = role;
}

}

public class PersonRole
{
String roleName;

public String getRole()
{
return role;
}

public void setRole(String roleName)
{
this.roleName = roleName;
}
}


Add person.xml as follows:

<beans>
<beans>
<bean id="personBean" class="test.PersonImpl">
<constructor-arg><ref bean="personRoleBean"/></constructor-arg>
<property name="address">
<value>50 Grand Central Road</value>
</property>
<property name="personRole">
<ref local="personRoleBean"/>
</property>
</bean>

<bean id="personRoleBean" class="test.PersonRole"/>

</beans>


TEST class


public class PersonTest
{
public static void main(String args[]) throws Exception
{
try
{
Resource resource = new ClassPathResource("person.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Person personBean = (Person)factory.getBean("personBean");
System.out.println(personBean.getAddress(args[0]));
}
catch(Exception e)
{
e.printStackTrace(e);
}

}

}

No comments: