Spring中Bean管理操作基于XML配置文件方法实现
基于XML配置文件方式实现
1、基于xml
方式创建对象
<bean id="user" class="com.action.spring.User"></bean>
- 使用标签中添加对应属性
id
属性:对象别名,唯一标识。class
属性:类全路径(包加类名)。
- 创建对象默认执行无参构造函数。
2、基于xml
方式注入属性
-
DI
:依赖注入-
使用set方法注入
1、创建类,定义属性和对应的set方法
public class Book{ private String bname; private String bauthor; public void setBname(String bname){ this.bname = bname; } public void setBauthor(String bauthor){ this.bauthor = bauthor; } public void testBook(){ System.out.println(bname+"::"+bauthor); } }
2、在Spring配置文件中配置对象创建,配置属性注入
<bean id="book" class="com.action.spring.Book"> <!-- name:类里面属性名称; value:向属性中注入的值; --> <property name="bname" value="易筋经"></property> <property name="bauthor" value="少林和尚"></property> </bean>
注意: 此种方法必须保证类中有
set方法
来对属性进行操作。运行结果:
-
有参构造注入属性
package com.action.spring; public class Orders { private String oname; private String address; public Orders(String oname, String address) { this.address = address; this.oname = oname; } public void ordertest() { System.out.println(oname+"::"+address); } }
注意:
ApplicationContext context = new FileSystemXmlApplicationContext("src/config/bean1.xml");
在加载过程中创建实例时,会默认调用无参构造函数,当创建有参构造函数之后,在创建实例的时候会报错。<bean id="orders" class="com.action.spring.Orders"></bean>
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orders' defined in file [E:\workspace\Springwork\src\config\bean1.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.action.spring.Orders]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.action.spring.Orders.<init>()
此时需要使用完整的有参函数注入属性的方法。
<bean id="orders" class="com.action.spring.Orders"> <constructor-arg name="oname" value="电脑"></constructor-arg> <constructor-arg name="address" value="正弘城"></constructor-arg> </bean>
此时即可调用方法。
ApplicationContext context = new FileSystemXmlApplicationContext("src/config/bean1.xml"); Orders orders = context.getBean("orders", Orders.class); orders.ordertest();
运行结果:
-