(三)Spring IOC - xml配置初级使用

xml配置初级使用

1.搭建Maven项目,并在pom引入依赖

(img-jJ78SEJv-1650293001889)(https://secure2.wostatic.cn/static/tDEnzqfuZoe7gaE3jSzZkc/image.png)]

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.19.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>RELEASE</version>
    <scope>test</scope>
</dependency>

2.容器的实例化和使用

  • 创建Spring的配置文件 spring_ioc_base.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    </beans>       
    
  • 创建单元测试,测试Spring项目启动加载配置文件
    在这里插入图片描述

  • ApplicationContext详解

    创建spring上下文,加载所有的bean

    • ClassPathXmlApplicationContext 根据项目路径的xml配置实例化spring容器
    • FileSystemXmlApplicationContext 根据磁盘路径的xml配置实例化spring容器
    • AnnotationConfigApplicationContext 根据javaConfig配置实例化spring容器

    对象在Spring容器创建完成的时候就已经创建完成,不是需要用的时候才创建。

3. 创建User对象

public class User {
   

    private Integer id;
    private String name;
    private Integer age;
    private String address;
    private String job;
    
    getter and setter...
}    

4. bean的使用

在xml文件中为User对象配置一个bean,使用标签

<!--配置bean-->
<!--默认使用无参构造函数-->
<bean class="com.lazy.entity.User" id="user" />
<!--使用name设置别名,可以使用 空格 , ;-->
<bean class="com.lazy.entity.User" id="user1" name="user2 user3,user4;user5"/>
<!--配置bean别名-->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值