spring bean的配置(一)

本文详细介绍了 Spring 框架中 Bean 的配置方法,包括基本的 XML 配置方式,如何通过 id 和 class 属性定义 Bean,以及如何利用 constructor-arg 和 property 元素进行依赖注入。

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

案例一:

<?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="..." class="...">
        <!-- configuration for this bean go here -->
    </bean>
        <!-- configuration for this bean go here -->
    <bean id="..." class="...">

    </bean>
    <!-- more bean definitions go here -->
</beans>

id属性:定义单个bean组件的命名。

class属性:定义了bean使用的类,要使用类的全称来定义。(fully qualified classname)

案例二:

<bean id="car" class="com.yl.Car">
    <constructor-arg value="Audi"/>
    <constructor-arg ref="Shanghai"/>
    <constructor-arg value="300000"/>
</bean>

在构造bean的时候,可以使用constructor-arg元素来提供额外信息,如果不配置constructor-arg元素,spring将会使用bean的默认构造器。

value属性:赋予构造参数的属性值,此构造参数应为简单类型。
ref属性:把bean的引用赋予给构造器。

案例三:

package web;

public class Tom {
    private int number;
    private PersonalInfo personalInfo;
    public Tom() {

    }
    public void setNumber(int number) {
        this.number = number;
    }
    public void serPersonalInfo(PersonalInfo personalInfo) {
        this.personalInfo = personInfo;
    }
}
<bean id="tom" class="web.Tom">
    <property name="number" value="15"/>
    <property name="personalInfo" ref="scoreList"/>
</bean

如果spring使用setter方式注入,要使用property元素来给bean提供信息。

name属性:表示要注入bean的beans属性名。
value属性:表示给bean属性注入的值。
ref属性:表示给bean属性注入另一个bean的引用

property元素会指示spring调用set()方法来为属性设置值,也会根据bean属性的类型来判断value值的正确类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值