Professional Documents
Culture Documents
The Dependency Injection (DI) feature is the core architectural foundation of the Spring
framework. This lab explores various basic dependency injection schemes of Spring framework
Expected duration: 60 minutes
Resources
Lab Exercises
Most exercises in this lab are provided in the form of "ready-to-open-and-run" Maven projects in
order to maximize the effectiveness of the learning process. You are welcome to create them from
scratch. It is also strongly encouraged you do as much experimentation of your own by changing
the provided code.
Create a new "Java Working Set" called "spring3_di_basics" (or whatever name of
your choice). This is to organize the projects under the working set.
How to set simple values to the properties of a bean using Dependency Injection.
Tasks to be performed
1.
2.
String name;
int age;
float height;
boolean isProgrammer;
Long ageInSeconds;
2. beans.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- injecting built-in vals sample -->
<bean id="injectSimple" class="com.softwarecampus.examples.Main">
<property name="name">
<value>John Smith</value>
</property>
<property name="age">
<value>35</value>
</property>
<property name="height">
<value>1.78</value>
</property>
<property name="isProgrammer">
<value>true</value>
</property>
<property name="ageInSeconds">
<value>1103760000</value>
</property>
</bean>
</beans>
Tasks to be performed
1.
2.
Tasks to be performed
1.
2.
true
true
true
aliases = name2 name3
s1
s2
s3
s4
=
=
=
=
(String)factory.getBean("name1");
(String)factory.getBean("name2");
(String)factory.getBean("name3");
(String)factory.getBean("name4");
System.out.println((s1 == s2));
System.out.println((s2 == s3));
System.out.println((s3 == s4));
String[] x = factory.getAliases("name3");
System.out.println("aliases = " + x[0] + " " + x[1]);
}
2. beans.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- naming examples -->
<bean id="string1" class="java.lang.String"/>
<bean name="string2" class="java.lang.String"/>
<bean class="java.lang.String"/>
<!-- aliasing examples -->
<bean id="name1" name="name2,name3,name4" class="java.lang.String"/>
</beans>