【Spring学习笔记】2.IOC初体验

第一个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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值