新建一个苹果类
public class Apple{
private String title;
private String color;
private String origin;
public Apple(String title,String color,String origin){
this.title=title;
this.color=color;
this.origin=origin;
}
...setter getter
}
新建孩子类
public class Child{
private String name;
private Apple apple;
public Child(){
}
public Child(String name,Apple apple){
}
...setter getter
public void eat(){
System.out.println(name+"吃到了"+apple.getOrigin()+"种植的"+apple.getTitle());
}
}
添加maven依赖
org.springframework spring-context 5.2.6.RELEASE
新建IoC配置文件, 并写下苹果和孩子的配置, 在Resource目录下新建applicationContext.xml
代码中可以获取lily和sweetApple的实例
//创建IoC容器, 并加载配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Apple sweetApple=contet.getBean("sweetApple",Apple.class);
Child lily=context.getBean("lily",Child.class);
这里就简单了演示了如何使用IoC帮助我们实例化对象
如果有多个配置文件怎么办?我们可以传入一个字符串数组对象实例化ApplicationContext
String[] configLocations =new String[]{"classpath:applicationContext.xml","classpath:applicationContext-1.xml"};
ApplicationContext context = new ClassXmlApplicationContext(configLocations);



