标签:use 创建 conf cat tor span XML class spring注入
Bean管理指的是Spring创建对象和Spring注入属性
Spring创建对象即之前所说的使用xml配置 id 和 class. Spring注入属性(也称注入依赖)有两种方式: 使用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(); } }
测试结果:
标签:use 创建 conf cat tor span XML class spring注入
原文地址:https://www.cnblogs.com/Ryan368/p/13858897.html