A Developer's Diary

Dec 19, 2012

Spring Framework - Constructor Injection

Constructor Injection is another basic operation performed by the Spring Framework. The AppTest class tests the validity of the service name property set via Constructor 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 constructor argument
 */
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 Beans configuration file service-beans.xml. The file displays the service name property being set through Constructor Injection
<?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">
  <constructor-arg value="TimerService" />
 </bean>
</beans>

The Service bean class. Please note that there is no setter here for setting the service name property
package com.examples.spring;

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

 public Service(String serviceName) {
  this.serviceName = serviceName;
 }

 public String getServiceName() {
  return serviceName;
 }
}

Output

No comments :

Post a Comment