> 文章列表 > 实验4---Spring IoC-xml配置

实验4---Spring IoC-xml配置

实验4---Spring IoC-xml配置

Spring IoC-xml配置

一.实验任务

通过该实验掌握利用Spring xml配置方式实现控制反转IoC(依赖注入),掌握Spring的Ioc注入方式:属性注入和构造注入。

二、实验结果

1 关键代码

1.1注入普通类及属性

1.Person的代码

public class Person {

private String name;

public void sayHello(){

System.out.println("hello, i am " + name);

}

//省略get set等

}

2.spring的xml配置文件关键代码

<!-- 配置简单类及属性 -->

<bean id="person" class=" sdjzu.springIoc.Person">

<property name="name" value="test"/>

</bean>

3.MyTest.java代码

public class MyTest{

public static void main(String[] args) {

ApplicationContext apc = new ClassPathXmlApplicationContext("applicationContext.xml");

Person person = (Person) apc.getBean("person");

person.sayHello();

}

}

4.运行效果图

1.2配置类及使用bean—设值(属性)注入

1.在applicationContext.xml的关键代码

<!--配置类及使用bean -->

<bean id="stoneAxe" class="sdjzu.propertyInject.StoneAxe"/>

<bean id="steelAxe" class="sdjzu.propertyInject.SteelAxe"/>

<bean id="chinese" class="sdjzu.propertyInject.Chinese">

<property name="axe" ref="steelAxe"></property>

</bean>

<bean id="american" class="sdjzu.propertyInject.American">

<property name="axe" ref="stoneAxe"></property>

</bean>

2.MyTest2.java代码

public class MyTest2{

public static void main(String[] args) {

ApplicationContext apc = new ClassPathXmlApplicationContext("applicationContext.xml");

//second 配置类及使用bean

Chinese chinese = (Chinese) apc.getBean("chinese");

chinese.useAxe();

American american = (American) apc.getBean("american");

american.useAxe();

}

}

3.效果图

1.3配置类及使用bean--构造注入

1.applicationContext.xml的关键代码

<!--构造器注入的方式-->

<bean id="france" class="sdjzu.propertyInject.France">

<constructor-arg ref="steelAxe"></constructor-arg>

<constructor-arg ref="stoneAxe"></constructor-arg>

<constructor-arg value="构造注入"></constructor-arg>

</bean>

2.MyTest3.java关键代码

public class MyTest3 {

public static void main(String[] args) {

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

//构造注入

France france=(France)context.getBean("france");

france.useAxe();

}

}

3.效果图