Bean管理指的是Spring创建对象和Spring注入属性
Spring创建对象即之前所说的使用xml配置 id 和 class. Spring注入属性(也称注入依赖)有两种方式: 使用set方法进行注入和使用有参构造进行注入
使用set方法注入属性示例:
类文件:
package com.ryan.spring5; public class ClassTestSet { String name; Integer age; public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } public void test(){ System.out.println(name + "::" + age); } }
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.xsd"> <!--配置User对象创建--> <bean id="animal" class="com.ryan.spring5.ClassTestSet"> <property name="age" value="4"></property> <property name="name" value="Doggy"></property> </bean> </beans>
调用对象文件:
public class TestSpring5 { public static void main(String[] args){ //1.加载Spring配置文件 ApplicationContext context = new FileSystemXmlApplicationContext("conf\beans1.xml"); //2.获取配置创建的对象 ClassTestSet animal = context.getBean("animal", ClassTestSet.class); animal.test(); } }
测试结果:
使用有参构造函数注入属性实例:
类文件:
package com.ryan.spring5; public class ClassTestConstruction { String name; int age; public ClassTestConstruction(String name, int age) { this.name = name; this.age = age; } public void test(){ System.out.println(name + "::" + age); } }
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.xsd"> <!--配置User对象创建--> <bean id="person" class="com.ryan.spring5.ClassTestConstruction"> <constructor-arg name="name" value="章北海"></constructor-arg> <constructor-arg name="age" value="30"></constructor-arg> </bean> </beans>
或(index=0表示第一个参数, index=1表示第二个参数):
<?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"> <!--配置User对象创建--> <bean id="person" class="com.ryan.spring5.ClassTestConstruction"> <constructor-arg index="0" value="章北海"></constructor-arg> <constructor-arg index="1" value="30"></constructor-arg> </bean> </beans>
调用对象文件:
public class TestSpring5 { public static void main(String[] args){ //1.加载Spring配置文件 ApplicationContext context = new FileSystemXmlApplicationContext("conf\beans1.xml"); //2.获取配置创建的对象 ClassTestConstruction person = context.getBean("person", ClassTestConstruction.class); person.test(); } }
测试结果:
*注: 此外还有一种使用p名称空间注入属性的方式, 需要修改xml约束, 用的不多, 暂不记录