spring的xml配置文件简单使用方法

本文介绍了Spring框架中XML配置文件的使用步骤,包括导入jar包、创建applicationContext.xml、定义Java类、配置类信息以及编写测试类进行验证。通过这些步骤,可以成功地在Spring中管理Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步、导入jar包

右键lib文件夹,选择add as library...

第二步、在src(类目录)下spring配置创建文件:applicationContext.xml(最好是直接用这个名字)

第三步、创建一个类并加上getter,setter,无参,满参构造,重写tostring

package com.atguigu.beans;

public class Actor {
    private int id;

    private String name;

    private int age;

    private double sales;

    public Actor() {
    }

    public Actor(int id, String name, int age, double sales) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sales = sales;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSales() {
        return sales;
    }

    public void setSales(double sales) {
        this.sales = sales;
    }



    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Actor{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sales=" + sales +
                '}';
    }
}

 第四步、在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="actor" class="com.atguigu.beans.Actor"/>
</beans>

第五步、写测试类

package com.atguigu.test;

import com.atguigu.beans.Actor;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ActorTest {

    @Test
    public void test01() {
        //获取application的上下文对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //通过字节码class去获取配置文件的对象
//        Actor actor = applicationContext.getBean(Actor.class);
        //通过配置文件里的id读取,得到Object对象,强转
        Actor actor = (Actor) applicationContext.getBean("actor");

        System.out.println(actor);
    }
}

 上图中注释和没注释的两种方法都可获取到actor对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值