【Spring第三篇】什么是Bean?

在Spring 中,构成应用程序主干并由Spring IoC容器管理的对象称为bean。bean是一个由Spring IoC容器实例化、组装和管理的对象。

我们总结如下:
1.bean是对象,一个或者多个不限定
2.bean由Spring中一个叫IoC的东西管理
3.我们的应用程序由一个个bean构成

比如我们建立一个实体类Hello

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Hello {
    private String str;
}

将这个类在beans.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-3.0.xsd">

    <bean id="hello" class="com.kk.pojo.Hello">
        <!--    set注入 获取Hello中的属性str 并且给str赋值Spring-->
        <property name="str" value="Spring"/>
    </bean>

</beans>

使用Spring创建对象,在Spring中 这些都称为Bean

类型 变量名 = new 类型

Hello hello = new Hello()
bean id = new 对象()

id=变量名
class = new 的对象((Hello))

property 相当于给对象中的属性设置值

其核心就是,给属性str使用set进行赋值

 public void setStr(String str) {
    this.str = str;
}

测试:

public class Test {

    public static void main(String[] args) {
        //获取Spring的上下文对象 获取其中resources目录下的beans.xml文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        Hello hello = (Hello) context.getBean("hello"); //获取bean中参数id为hello
        System.out.println(hello.toString());
    }
}

获取Spring的上下文对象,使用getBean获得bean中的id,即可获得Hello这个对象并且获得赋给ta的值

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tzrDLgXL-1649572935721)(C:\Users\30666\AppData\Roaming\Typora\typora-user-images\image-20220309235849209.png)]


  • 5
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不易撞的网名

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值