【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中注册


<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">
        
        <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)]


你可能感兴趣的:(Spring,Spring,框架)