Showing posts with label spring-di/ioc. Show all posts
Showing posts with label spring-di/ioc. Show all posts

Thursday, April 14, 2011

Spring – How to pass a Date into bean property (CustomDateEditor )


Simple method may not work
Generally, Spring developer are not allow to pass a date format parameter into bean property via DI.

For example,

public class CustomerService
{
    Date date;
 
    public Date getDate() {
        return date;
    }
 
    public void setDate(Date date) {
        this.date = date;
    }
 
}

Bean configuration file
<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.5.xsd">
 
   <bean id="customerService" class="com.services.CustomerService">
       <property name="date" value="2010-01-31" />
   </bean>
 
</beans>

Run it

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.mkyong.customer.services.CustomerService;
 
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext context = 
          new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
 
        CustomerService cust = (CustomerService)context.getBean("customerService");
        System.out.println(cust.getDate());
    }
}

Error message prompt.

Caused by: org.springframework.beans.TypeMismatchException:
Failed to convert property value of type [java.lang.String] to
required type [java.util.Date] for property 'date';

nested exception is java.lang.IllegalArgumentException:
Cannot convert value of type [java.lang.String] to
required type [java.util.Date] for property 'date':
no matching editors or conversion strategy found

Solution

There are two solutions available.

1. Factory bean

Declare a dateFormat bean, and reference it as a factory bean from the date property. The factory method will call the SimpleDateFormat.parse() menthod to convert the String into Date object automatically.

<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.5.xsd">
 
   <bean id="dateFormat" class="java.text.SimpleDateFormat">
    <constructor-arg value="yyyy-MM-dd" />
   </bean>
 
   <bean id="customerService" class="com.mkyong.customer.services.CustomerService">
       <property name="date">
           <bean factory-bean="dateFormat" factory-method="parse">
            <constructor-arg value="2010-01-31" />
        </bean>
    </property>
   </bean>
 
</beans>

2. Property editors (CustomEditorConfigurer + CustomDateEditor)

Declare a CustomDateEditor class to convert the String into java.util.Date properties.

<bean id="dateEditor"
       class="org.springframework.beans.propertyeditors.CustomDateEditor">
 
    <constructor-arg>
        <bean class="java.text.SimpleDateFormat">
            <constructor-arg value="yyyy-MM-dd" />
        </bean>
    </constructor-arg>
    <constructor-arg value="true" />
 
  </bean>

Register the CustomDateEditor in CustomEditorConfigurer, so that the Spring will convert the properties whose type is java.util.Date.


<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
        <property name="customEditors">
            <map>
            <entry key="java.util.Date">
                <ref local="dateEditor" />
            </entry>
            </map>
        </property>
    </bean>

Bean configuration file.

<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.5.xsd">
 
  <bean id="dateEditor"
    class="org.springframework.beans.propertyeditors.CustomDateEditor">
 
    <constructor-arg>
        <bean class="java.text.SimpleDateFormat">
            <constructor-arg value="yyyy-MM-dd" />
        </bean>
    </constructor-arg>
    <constructor-arg value="true" />
 
  </bean>
 
  <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
       <map>
        <entry key="java.util.Date">
            <ref local="dateEditor" />
        </entry>
       </map>
    </property>
   </bean>
 
   <bean id="customerService" class="com.mkyong.customer.services.CustomerService">
       <property name="date" value="2010-02-31" />
   </bean>
 
</beans>




Saturday, March 26, 2011

Spring 3.0 with EL

Spring 3.0 introduces support for expression language, which is similar to Unified EL support in jsp. The intention was to further provide different ways of setting bean properties.
The advantage of EL is that it can support different kinds of expressions like Boolean, literal ,regular , method invocation, etc.

It is also called spEL or spring EL.
Now again there are 2 methods of using EL notation - xml and annotations.

Example :
public class ErrorHandler {

    private String defaultLocale;
    
    public void setDefaultLocale(String defaultLocale) {
        this.defaultLocale = defaultLocale;
    }
    
    public void handleError() {
        //some error handling here which is locale specific
        System.out.println(defaultLocale);
    }
}

Using EL in xml  config :

<bean id="errorHandler" class="xxxx.ErrorHandler">
    <property name="defaultLocate" value="#{systemProperties['user.region']}" />
</bean>

Annotation style config:

import org.springframework.beans.factory.annotation.Value;

public class ErrorHandler {

    @Value("#{ systemProperties['user.region'] }")
    private String defaultLocale;
    
    public void handleError() {
        //some error handling here which is locale specific
        System.out.println(defaultLocale);
    }
}
Prior to Spring 3.0 , the only way to provide configuration metadata was XML.

Sunday, March 20, 2011

Spring : DisposableBean Interface and InitializingBean

The InitializingBean and DisposableBean are two marker interfaces which call the  afterPropertiesSet() for the begining and destroy() for the last action of initialization and    destruction to be performed.

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class StudentService implements InitializingBean, DisposableBean {
String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public void afterPropertiesSet() throws Exception {
System.out.println(" After properties has been set : " + message);
}

public void destroy() throws Exception {
System.out.println("Cleaned everything!!");
}

}


In context.xml bean is created in usual style.

Spring List Property Example

The Spring Framework has bean support for the Collections. It provide list, set, map and props elements. Here in this tutorial you will see about the list elements which is used to set values inside the list.

Example

Consider this list bean :

import java.util.List;

public class CollegeBean {
private List<Object> lists;

public List<Object> getLists() {
return lists;
}

public void setLists(List<Object> lists) {
this.lists = lists;
}

@Override
public String toString() {
return "College [lists=" + lists + "]";
}
}


Simplebean


public class StudentBean {
private String name;
private String address;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

@Override
public String toString() {
return "Student [address=" + address + ", name=" + name + "]";
}
}


context.xml


<!-- Spring List Property Example  -->

<bean id="studentBean" class="com.xxx.StudentBean">
<property name="name" value="satya" />
<property name="address" value="Delhi" />
</bean>

<bean id="collegeBean" class="com.xxx.CollegeBean">

<property name="lists">
<list>
<value>1</value>
<ref bean="studentBean" />
<bean class="com.xxx.StudentBean">
<property name="name" value="ankit" />
<property name="address" value="delhi" />
</bean>
</list>
</property>
</bean>

<!-- End -->

Spring : Lifecycle interface

Lifecycle interface is basically meant for managing startup and shutdown callbacks. For eg., on startup we would like to load data into the cache and on shutdown just clear the cache or start the process at startup and end it when exiting.

So SmartLifecycle is extension of Lifecycle Interface.

Example :

import org.springframework.context.SmartLifecycle;

public class LifecycleImpl implements SmartLifecycle {

public LifecycleImpl() {
System.out.println("LifecycleImpl class instantiated..");
}

@Override
public boolean isAutoStartup() {
System.out.println("isAutoStartup method our LifecyleImpl class called..");
return true;
}

@Override
public void stop(Runnable r) {
System.out.println("stop(Runnable) method of our LifecycleImpl class called..");
r.run();
}

@Override
public boolean isRunning() {
System.out.println("isRunning method of our LifecycleImpl class called..");
return true;
}

@Override
public void start() {
System.out.println("start method of our LifecycleImpl class called..");
}

@Override
public void stop() {
System.out.println("stop method of our LifecycleImpl class called..");
}

@Override
public int getPhase() {
System.out.println("getPhase method of our LifecycleImpl class called..");
return 1;
}
}



Create the bean in simple way in context.xml.

Spring Map Example

In this example you will see how bean is prepared for injecting Map collection type key and its values.

import java.util.Iterator;
import java.util.Map;

public class MapBean {
private Map<String, Integer> student;
public void setDetails(Map<String, Integer> student) {
this.student = student;
}
public void showDetails() {
Iterator it = student.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}
}


In the config file :


<bean id="mapbean" class="com.xxxx.MapBean">
<property name="details">
<map>
<entry key="Satya" value="101"/>
<entry key="Rohit" value="102"/>
<entry key="Aniket" value="103"/>
</map>
</property>
</bean>

BeanFactoryPostProcessor interface

The semantics of this interface is similar to BeanPostProcessor but with one major difference : BeanFactoryPostProcessor operate on bean configuration metadata; So spring IoC container allow BeanFactoryPostProcessor to read the configuration metadata and potentially change it before the container instantiates any bean other than BeanFactoryPostProcessor .

But if you want to change the actual bean instances( the objects that are created from the configuration metadata), then use BeanPostProcessor.

Example …

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class BeanFactoryPostProcessorImpl implements BeanFactoryPostProcessor {

public BeanFactoryPostProcessorImpl() {
System.out.println("BeanFactoryPostProcessorImpl class instantiated..");
}

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
throws BeansException {
System.out.println("postProcessBeanFactory method of our BeanFactoryPostProcessorImpl class called..");

//dynamically registering a new bean in the context. you can try this later on.
//similar to @Configuration and @Bean we saw in previous section.
//factory.registerSingleton("myBean", new SampleBean());
}
}



Again one of the commonly used BeanFactoryPostProcessor is PropertyPlaceHolderConfigurer class. We already have seen the usage of this class before. This replaces the config of any bean containing ${}  with the actual property value so by the time the bean is instantiated, the correct values are already in the container.

@Required annotation

BeanPostProcessor is used by the framework heavily. One of the best example is RequiredAnnotationBeanPostProcessor class. In spring we require @Required annotation to make it a mandatory dependency, that thas to be injected.

Just by using annotation in the code will not work, since someone has to check whether the requirement has been met or not and reposrt an error it not.

Example

//The service
public interface BankService {

public BillPaymentService getBillPaymentService();
public CustomerService getCustomerService();
}

//The impl class
public class BankServiceImpl implements BankService {

private CustomerService customerService;
private BillPaymentService billPaymentService;

@Required
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}

@Required
public void setBillPaymentService(BillPaymentService billPaymentService) {
this.billPaymentService = billPaymentService;
}

public BillPaymentService getBillPaymentService() {
return billPaymentService;
}

public CustomerService getCustomerService() {
return customerService;
}
}


Now here we have mentioned what is required, but we need RequiredAnnotationBeanPostProcessor to check whether these required dependency are injected or not.


The configuration


<!--  According the code, we need to set both the dependencies.
Comment out one or both the property tag and see the error -->
<bean id="bankService" class="com.xxxx.BankServiceImpl">
<property name="billPaymentService" ref="billPaymentService" />
<property name="customerService" ref="customerService" />
</bean>

<!-- Just by using @Required will not work. Someone has to parse it
and that's the role of this class -->
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />


Spring : BeanPostProcessor interface

The interface BeanPostProcessor allows custom modification of all new bean instance like for example making for marker interfaces or wrapping them with all proxies. The advance of interface BeanPostProcessor is that it auto-detect BeanPostProcessor beans in their bean definations and apply all beans before any others get created.

So it provides callback methods thaty you can implement to provide your own instantiation logic, dependency resolution logic and so forth. In a way you override default container's logic.

You can control the order in which these BeanPostProcessor interfaces execute by setting the order property only if the BeanPostProcessor implements the Ordered Interface.

Classes which implement BeanPostProcessor are special and treaded differently by container. All BeanPostProcessor and their directly referenced beans are instantiated on startup, as a part of the special startup phase of the ApplicationContext.

Example:

 

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

class StudentBean implements BeanPostProcessor {

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {

System.out.println("Before initialization : " + beanName);


return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {

System.out.println("After initialization : " + beanName);
return bean;
}
}



So BeanPostProcessor implementation gives us chance to perform custom processing before and after any bean is initialized.


In config.xml


<bean id="studentBean" class="com.roseindia.common.StudentBean" />

@PostConstruct and @PreDestroy example

In this tutorial you will learn how to implement the @PostConstruct and @PreDestroy which work similar to init-method and destroy-method in bean configuration file or implement the InitializingBean and DisposableBean in your bean class. To use @PostConstruct and @PreDestroy you have to register the CommonAnnotationBeanPostProcessor at bean configuration or specifying the <context:annotation-config /> in the bean configuration file.

Consider the service bean:

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class StudentService {

String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

@PostConstruct
public void initIt() throws Exception {
System.out.println("After properties has been set : " + message);
}

@PreDestroy
public void cleanUp() throws Exception {
System.out.println("Cleaned Everyting");
}

}


Bean config file:


<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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"
>

<context:annotation-config />

<bean id="studentService" class="com.xxxx.StudentService">
<property name="message" value="property message" />
</bean>

</beans>


Spring : init-method and destroy-method

In this first example, I’ll show you how the lifecycle of a bean happens within the xml-configfile.

In the xml-file, we can define an init- and destroy-method to the bean, which will be called automatically by Spring.
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: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"
>
<!-- -->
<bean id="attributesTest" class="a.Test" init-method="initMethod"
destroy-method="destroyMethod">
</bean>

</beans>

 

Now consider our bean with these 2 methods into it:

 

public class LifeCycledBean2{    
//
public LifeCycledBean2(){
System.out.println("We are in the constructor of LifeCycledBean2");
}
public void initMethod()
{
System.out.println("We are in initMethod of LifeCycledBean2");
}
public void destroyMethod()
{
System.out.println("We are in destroyMethod of Test");
}
}




Main or Runner program
In this case, I’ll use AbstractApplicationContext because this Context has a function to destroy the Context which a normal ApplicationContext doesn’t have.

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JustATest {
public static void main(String[] args) {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("Config.xml");
ctx.registerShutdownHook();
Test test = ctx.getBean("attributesTest",Test.class);
}
}


The output will be:

We are in the constructor of Test
We are in initMethod of Test
We are in destroyMethod of Test

It’s also possible to declare default init- and destroy-methods in the xml-file. This is done in the beans-tag:

<?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"

default-init-method="initMethod"
default-destroy-method="destroyMethod"
>
...

Spring : BeanNameAware Interface

Consider the following bean:

import org.springframework.beans.factory.BeanNameAware;

public class LifeCycledBean implements BeanNameAware
{
private String languageName;
private String beanName;

public LifeCycledBean ()
{
}

public String getLanguageName()
{
return languageName;
}

public void setLanguageName(String languageName)
{
this.languageName = languageName;
}

@Override
public void setBeanName(String beanName)
{
this.beanName = beanName;
}

public String getBeanName()
{
return beanName;
}
}


The above sample class provides one such implementation and the below client code uses the above class to know the name of the bean.

static void beanNameAwareTest()
{
Resource resource = new FileSystemResource("./src/resources/bean-lifecycle-1.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);
LanguageBean lifeCycledBean= (LanguageBean)beanFactory.getBean("lifeCycledBean");
System.out.println(lifeCycledBean.getLanguageName());
System.out.println(lifeCycledBean.getBeanName());
}



The following piece of Xml code snippet goes into the Xml Configuration file.

<bean id="javaLanguage" class="com.xxxx.LifeCycledBean">
<property name="lifeCycledBean" value="Java"/>
</bean>

Can an Innerclass be instantiated in Spring?

Dont be surprise but the answer is yes..

package com.src;
public class MyClass{
public static class InnerClass{
}
}


In spring.xml it Innerclass can be instantiated as:

<bean id="myclass" class="com.src.MyClass$InnerClass" />



Wow !! this is good , spring is amazing.The innerclass should be public and static only.
But i am wondering ,will  there be any real significance left of InnerClass or not?

Managing Property files with spring

There are few subtle complexities to managing properties in an enterprise Java Spring application, and if we are able to give fore-thought to it in design, one can yield big savings in terms of time, confusion, bugs, and gray hair down the road. 


So what we mean by properties ? Please refer here for this.

Fortunately for us, the Spring framework, with the PropertyPlaceholderConfigurer and PropertyOverrideConfigurer, provides the features and hooks we need to manage these cases (with the exception “dynamic” properties).


Please see PropertyPlaceholderConfigurer here. We can also set properties in a property file without even using placeholders in xml file with PropertyOverrideConfigurer.


Tips

Given the different possible types of properties, and Spring’s property framework, here are a few tips for managing them:
1) Consider using a JVM System property that sets the environment of the machine (e.g. “my.env=TEST”), telling the configurer which property file to use. For example:

<context:property-placeholder location="classpath:db-${my.env}.properties"/>

If the “my.env” property was set to “TEST”, then obviously the PropertyPlacementConfigurer would look for a file called “db-TEST.properties”. For Tomcat, this property can be set in the admin console or defined in a startup script (e.g. “-Dmy.env=TEST”) - neither of which is very elegant. Alternatively, it is possible to use JNDI with Tomcat, defining “my.env” in the server.xml and the context.xml of the web app. (Note, there are of course many other ways to solve this environment-specific problem, but this is an easy and relatively straight-forward one.)

2) It may be necessary to set the ignoreUnresolvablePlaceholders to true for any PropertyPlaceholderConfigurer, which will ensure that a configurer won’t fail if it can’t find a property. Why would this be a good thing? Oftentimes, one context file will import other context files, and each may have their own configurer. If ignoreUnresolvablePlaceholders is set to false (the default), then one configure would fail if it couldn’t find the property, even if another configurer down-stream could find it (see good explanation here). Beware, however, since this will suppress warnings for legitimate missing properties, making for some tough-to-debug configuration problems.

3) To encrypt properties, subclass the PropertyPlacementConfigurer and override the convertPropertyValue() method. For example:

protected String convertPropertyValue(String strVal) {
  //if strVal starts with “!!” then return EncryptUtil.decrypt(strVal)
  // else return strVal
}

4) Consider using the systemPropertiesMode property of the configurer to override properties defined in property files with System properties. For one-off environment specific properties this can be a helpful solution, however, for defining many properties, this configuration can be cumbersone.

5) For properties that need to be managed outside of the WAR, consider using a System property to define where the file is located. For example, the property ${ext.prop.dir} could define some default directory on the file system where external property files are kept:

<context:property-placeholder location="file:///${ext.prop.dir}db.properties"/>

This entails, however, that this property is set for any process that leverages the Spring container (e.g. add the param to the Run Configuration for integration/unit tests, etc.), otherwise the file would not be found. This can be a pain. To circumvent, the configurer can be overridden – changing the behavior such that it looks to the external directory only if the System property is set, otherwise it pulls from the classpath.

6) Beware of redundancy of environment-specific properties. For example, if the solution is to have one property file for each environment (e.g. “db-test.properties”, “db-dev.properties”, etc.), then maintaining these properties can be a bit of a nightmare - if a property “foo” is added, then it would have to be added to the property file for each environment (e.g. DEV, TEST, PROD, etc.). The PropertyOverrideConfigurer is appropriate to eliminate this redundancy, setting the default value in the application context itself, but then the overriding value in a separate file. It’s important, however, to document this well, since it can look a bit “magical” to an unsuspecting maintenance developer who sees one value specified in the context file, but another used at runtime.

Conclusion

Managing properties for an enterprise application is a little trickier than one might expect. With Spring’s property configurers, however, the toughest part is just knowing what you need - the rest comes out of the box, or with some minor extensions.


Spring : PropertyOverrideConfigurer

This class help us to set the bean properties in a property file without even using placeholders in the xml file.

We can define bean the usual way:

<!--  The properties of the bean are missing in the xml as we will load them
from the properties file -->
<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" />

Consider the property file:

#db2.properties
myDataSource.driverClassName=com.mysql.jdbc.Driver
myDataSource.url=jdbc:mysql://localhost:3306/test
myDataSource.username=root
myDataSource.password=


Now to refer to the location of properties file.

 

Old-style config:


<!-- Old style configuration-->
<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
<property name="location" value="classpath:package-com.xxxx/db2.properties" />
</bean>



New style config : Use property-override


<!-- Using context schema to achieve the same -->
<context:property-override location="classpath:packageXXXX/db2.properties" />

Spring : Configuring properties file with PropertyPlaceholderConfigurer

Consider the old db-config file :

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>


So we can see here we have hard-coded the properties of the database into the file, but rather than doing this, we can make our application more configurable, by placing these properties in the separate file and use ant-style ${property-name} syntax in xml file.


Defining the properties file


Suppose we define our db.properties file :


#db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
pass=


 


Referring to the properties file in spring config file


Now suppose we have properties file in some external configurable file, we can simply pickup values from them.


<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="username" value="${db.user}"/>
<property name="password" value="${db.password}"/>
...
</bean>


Using the p-namespace, the same file becomes:


<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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"

xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p">

<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${driver}"
p:url="${url}"
p:username="${user}"
p:password="${pass}"/>




Now once the bean is defined, we have to still tell the spring, to refer the property file location.


So this can be done in one of the 2 ways below:


Old style configuration


<!-- Old style configuration. Test one at a time by commenting the other -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:some package path/db.properties" />
</bean>


New style configuration : Use context: property-placeholder


<!-- Using context schema to achieve the same -->
<context:property-placeholder location="classpath:some-package-path/db.properties" />

Chitika