在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/beanshttp://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为helloSystem.out.println(hello.toString());}
}
获取Spring的上下文对象,使用getBean获得bean中的id,即可获得Hello这个对象并且获得赋给ta的值