Tuesday, 21 March 2017

Spring: Working with c-namespace

In my previous posts, I explained how to work with p-name space. Spring also provides c-namespace, where you can configure constructor arguments inline, rather than by using constructor-arg element.

Example
<bean id="531" name="kiran" class="com.sample.pojo.Employee">
 <constructor-arg name="lastName" value="Darsi" />
 <constructor-arg name="id" value="531" />
 <constructor-arg name="firstName" value="Kiran Kumar" />
</bean>

Above snippet can be written using c-namespace like below.

<bean id="531" name="kiran" class="com.sample.pojo.Employee" c:lastName="foo@bar.com" c:id="531" c:firstName="Kiran Kumar" />

Following is the complete working application.

Employee.java
package com.sample.pojo;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;

 public Employee(int id, String firstName, String lastName) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append("]");
  return builder.toString();
 }

}


myConfiguration.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:c="http://www.springframework.org/schema/c"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="531" name="kiran" class="com.sample.pojo.Employee"
  c:lastName="foo@bar.com" c:id="531" c:firstName="Kiran Kumar" />
  
</beans>

HelloWorld.java

package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.Employee;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Employee employee = context.getBean("kiran", Employee.class);

  System.out.println(employee);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java, you can able to see following output.

Employee [id=531, firstName=Kiran Kumar, lastName=foo@bar.com]




Previous                                                 Next                                                 Home

No comments:

Post a Comment