Springboot使用bean方式详解(附代码)

本文详细讲解了Springboot中使用bean的多种方法,包括通过Bean类和XML配置文件创建、@Configuration/@Bean注解创建、@Component注解结合@AutoWired或@Resource自动装配。重点介绍了在实际项目中最常用的@Component注解配合自动装配的方式。

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

上一章节中介绍了springboot创建bean的几种方式:注解形式(@Controller/@Service/@Component/@Repository)和@Configuration/@Bean组合注解形式;
本章节主要介绍如何在项目中使用创建的bean。
#####范例一:通过Bean类、xml配置文件创建bean并注入到容器中

//创建bean类
public class Computer {
   
   
    private String name;
    private String color;
    private Float price;

    public String getName() {
   
   
        return name;
    }

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

    public String getColor() {
   
   
        return color;
    }

    public void setColor(String color) {
   
   
        this.color = color;
    }

    public Float getPrice() {
   
   
        return price;
    }

    public void setPrice(Float price) {
   
   
        this.price = price;
    }

    @Override
    public String toString() {
   
   
        return "Computer{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", price=" + price +
                '}';
    }
}
<!--------通过applicationContext.xml配置文件实例化bean并注入Spring容器中-------->
<beans>
	<bean <
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值