通过该实验掌握利用Spring xml配置方式实现控制反转IoC(依赖注入),掌握Spring的Ioc注入方式:属性注入和构造注入。
1.Person的代码
| public class Person { private String name; public void sayHello(){ System.out.println("hello, i am " + name); } //省略get set等 } |
2.spring的xml配置文件关键代码
| |
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.在applicationContext.xml的关键代码
|
|
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.applicationContext.xml的关键代码
|
|
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.效果图

下一篇:求《与校霸同桌》全文