第一个IoC程序 - 演示如何使用Spring IoC
新建一个苹果类
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依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context<artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
新建IoC配置文件, 并写下苹果和孩子的配置, 在Resource目录下新建applicationContext.xml
<bean id="sweetApple" class="com.imooc.spring.ioc.entity.Apple">
<property name="title" value="红富士"></property>
<property name="origin" value="欧洲"></property>
<property name="color" value="红色"></property>
</bean>
<bean id="lily" class="com.imooc.spring.ioc.entity.Child">
<property name="name" value="莉莉" />
<property name="apple" ref="sweetApple" />
</bean>
代码中可以获取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);