Bean.java:
package com.lnn.ioc;
public class Bean {
private String text;
private double number;
public Bean(String
text, double number) {
this.text = text;
this.number = number;
}
public String
getText() {
return text;
}
public double getNumber() {
return number;
}
}
constructor.xml:
<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">
<!--
providing the values as per order -->
<bean id="bean1"
class="com.lnn.ioc.Bean">
<constructor-arg value="text"
/>
<constructor-arg value="4.5"
/>
</bean>
<!--
providing the values as by using name -->
<bean id="bean2"
class="com.lnn.ioc.Bean">
<constructor-arg name="text"
value="super text" />
<constructor-arg name="number"
value="4.5" />
</bean>
<!--
providing the values as by using type -->
<bean id="bean3"
class="com.lnn.ioc.Bean">
<constructor-arg type="java.lang.String"
value="super text" />
<constructor-arg type="double"
value="4.5" />
</bean>
<!--
providing the values as by using index -->
<bean id="bean4"
class="com.lnn.ioc.Bean">
<constructor-arg index="0"
value="super text" />
<constructor-arg index="1"
value="4.5" />
</bean>
<!--
providing the values as by using type not in order (not suggested) -->
<bean id="bean5"
class="com.lnn.ioc.Bean">
<constructor-arg type="double"
value="4.5" />
<constructor-arg type="java.lang.String"
value="super text" />
</bean>
</beans>
Test.java:
package com.lnn.ioc;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[]
args) {
ApplicationContext
context = new ClassPathXmlApplicationContext("ioc/constructor.xml");
Bean
bean1 = context.getBean("bean1", Bean.class);
System.out.println(bean1.getText());
System.out.println(bean1.getNumber());
Bean
bean2 = context.getBean("bean2", Bean.class);
System.out.println(bean2.getText());
System.out.println(bean2.getNumber());
Bean
bean3 = context.getBean("bean3", Bean.class);
System.out.println(bean3.getText());
System.out.println(bean3.getNumber());
Bean
bean4 = context.getBean("bean4", Bean.class);
System.out.println(bean4.getText());
System.out.println(bean4.getNumber());
Bean
bean5 = context.getBean("bean5", Bean.class);
System.out.println(bean5.getText());
System.out.println(bean5.getNumber());
}
}
No comments:
Post a Comment