栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【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依赖


    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);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/973048.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号