A Developer's Diary

Dec 19, 2012

Spring Framework - Setter Injection

The most elementary operation performed by the Spring Framework is setting the property value via Setter Injection. The AppTest class is a junit test class which validates the property set through setter injection.

package com.examples.spring;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * File: AppTest.java 
 * 
 * Setting property via Setter Injection
 */
public class AppTest {

 ApplicationContext ctx = null;

 @Before
 public void setup() {
  ctx = new ClassPathXmlApplicationContext("service-beans.xml");
 }

 @After
 public void cleanup() {
 }

 @Test
 public void testPropertyInjection() {
  Service srvc = (Service) ctx.getBean("myservice");
  Assert.assertEquals(srvc.getServiceName(), "TimerService");
 }
}

The service-beans.xml is the beans configuration file where service name property is defined
<?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.xsd">
    <bean id="myservice" class="com.examples.spring.Service">
        <property name="serviceName" value="TimerService"></property>
    </bean>
</beans>

The Service bean class which is instantiated by the Spring Framework
package com.examples.spring;

/**
 * File: Service.java
 */
public class Service {
 private String serviceName;

 public String getServiceName() {
  return serviceName;
 }

 public void setServiceName(String serviceName) {
  this.serviceName = serviceName;
 }
}

Output

No comments :

Post a Comment