Spring — Primitive Array / Secondary Array DI Parameters | Code Factory

Donate : Link

WordPress Blog : Link

Applications… : Link

Spring Tutorial Index Page: Link

Create Java Project

  • Open Eclipse
  • Go to File -> New -> Others… -> Java Project
  • Create DI-Array project
  • Right click on project -> Build Path -> Configure Build Path -> Libraries tab -> Add External JARs
    - commons-logging-X.X.jar
    - spring-beans-X.X.X.jar
    - spring-context-X.X.X.jar
    - spring-core-X.X.X.jar
    - spring-expression-X.X.X.jar
  • * You can find dtd information from spring-beans-X.X.X.jar -> org -> springframework -> beans -> factory -> xml -> spring-beans.dtd (line no 36 & 37)

spring.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="e1" class="com.codeFactory.beans.Engine">
<property name="modelYear" value="2001" />
</bean>
<bean id="e2" class="com.codeFactory.beans.Engine">
<property name="modelYear" value="2002" />
</bean>
<bean id="e3" class="com.codeFactory.beans.Engine">
<property name="modelYear" value="2003" />
</bean>
<bean id="c" class="com.codeFactory.beans.Car">
<property name="companyNames">
<list>
<value>JLR</value>
<value>Hummer</value>
<value>Audi</value>
</list>
</property>
<property name="engines">
<list>
<ref bean="e1" />
<ref bean="e2" />
<ref bean="e3" />
</list>
</property>
</bean>
</beans>

Car.java

package com.codeFactory.beans;import java.util.Arrays;/**
* @author code.factory
*
*/
public class Car {
private String companyNames[];
private Engine engines[];
public Car() {
System.out.println("Car.Car()");
}
public void setCompanyNames(String[] companyNames) {
this.companyNames = companyNames;
}
public void setEngines(Engine[] engines) {
this.engines = engines;
}
public void print() {
System.out.println("Company Name " + Arrays.toString(companyNames));
for (Engine engine : engines) {
System.out.println("Engine - Model Year " + engine.getModelYear());
}
}
}

Engine.java

package com.codeFactory.beans;/**
* @author code.factory
*
*/
public class Engine {
private int modelYear;
public Engine() {
System.out.println("Engine.Engine()");
}
public int getModelYear() {
return modelYear;
}
public void setModelYear(int modelYear) {
this.modelYear = modelYear;
}
}

Client.java

package com.codeFactory.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codeFactory.beans.Car;/**
* @author code.factory
*
*/
public class Client {
public static void main(String... args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/codeFactory/resources/spring.xml");

Car t = (Car) context.getBean("c");
t.print();
}
}

Output:

Engine.Engine()
Engine.Engine()
Engine.Engine()
Car.Car()
Company Name [JLR, Hummer, Audi]
Engine - Model Year 2001
Engine - Model Year 2002
Engine - Model Year 2003