基于xml的无参构造函数的IoC配置

0.配置pom.xml文件

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.3.1</version>
        </dependency>
    </dependencies>

1.编写组件类CustomComponent1.java

package com.my.ioc_01;

public class CustomComponent1 {

    // 默认包含无参构造函数

    public void customMethod() {
        System.out.println("这是组件类的一个自定义方法");
    }
}

2.编写配置文件applicationContext.xml

在resources目录下新建applicationContext.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">

    <bean id="customComponent1" class="com.my.ioc_01.CustomComponent1" />
</beans>

3.创建Spring IoC容器

在创建IoC容器之前,需要选择合适的容器实现类

实现类用途
ClassPathXmlApplicationContext读取类路径下的xml的配置方式
AnnotationConfigApplicationContext读取Java类的配置方式
WebApplicationContextweb项目专属的配置方式

本例程将xml文件放在了resources目录下,也就是放在了被编译后的类目录classes目录下,因此选用ClassPathXmlApplicationContext实现类来创建Spring IoC容器.

    /**
     * 选择合适的容器实现类,创建Spring IoC容器
     */
    public ApplicationContext createIoc() {
        // 此处配置文件可填写多个
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        return context;
    }

4.使用组件类对象

在使用组件类对象之前,我们需要先获取组件类对象,获取组件类对象需要调用getBean方法

获取到组件类对象之后,我们只需调用组件类对象的相应方法就可以了.

    /**
     * 通过Spring IoC容器获取组件类对象
     */
    public CustomComponent1 getBean() {
        ApplicationContext context = createIoc();
        CustomComponent1 customComponent1 = context.getBean("customComponent1", CustomComponent1.class);
        return customComponent1;
    }

    /**
     * 使用从Spring IoC获取到的组件类对象
     */
    @Test
    public void useBeans() {
        CustomComponent1 customComponent1 = getBean();
        customComponent1.customMethod();
    }

5.测试结果

6.相关文件下载

基于xml配置方式的无参构造函数的IoC配置相关文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值