【Spring】的【bean】管理(XML配置文件)

时间:2023-03-09 09:54:35
【Spring】的【bean】管理(XML配置文件)

Bean实例化的三种方式

说明:通过配置文件创建对象就称为Bean实例化。

第一种:使用类的无参构造创建(重点)

实体类

 package com.tyzr.ioc;
public class User {
private String username;
public User(String username) {
super();
this.username = username;
}
public User() {
}
public void add(){
System.out.println("--------->add");
}
public static void main(String[] args) {
//原始做法
//User user = new User();
//user.add();
}
}

配置文件

 <!-- IOC入门 -->
<bean id="user" class="com.tyzr.ioc.User"></bean>

测试类

 @Test
public void testUser(){
//加载核心配置文件,创建对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//得到我们配置的对象
//<bean id="user" class="com.tyzr.ioc.User"></bean>
User user = (User)context.getBean("user");
user.add();
}

问题:如果类里面没有无参构造方法会出现异常,如下:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'user' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.tyzr.ioc.User]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.tyzr.ioc.User.<init>(

第二种:使用静态工厂创建

创建静态的方法,返回类的对象。

实体类

 package com.tyzr.bean;
public class Bean2 {
public void bean2(){
System.out.println("bean2------------");
}
 package com.tyzr.bean;
public class Bean2Factory {
//静态方法返回bean2
public static Bean2 getBean2(){
return new Bean2();
}
}

配置文件

 <!-- 使用静态工厂创建对象 -->
<bean id="bean2" class="com.tyzr.bean.Bean2Factory" factory-method="getBean2"></bean>

测试类

 @Test
public void testBean2(){
//加载核心配置文件,创建对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//得到我们配置的对象
//<bean id="bean2" class="com.tyzr.bean.Bean2Factory" factory-method="getBean2"></bean>
Bean2 bean2 = (Bean2)context.getBean("bean2");
bean2.bean2();
}

第三种:使用实例工厂创建

创建不是静态的方法,返回类的对象。

实体类

 package com.tyzr.bean;
public class Bean3 {
public void bean3(){
System.out.println("bean3------------");
}
}
 public class Bean3Factory {
//普通方法返回bean3
public Bean3 getBean3(){
return new Bean3();
}
}

配置文件

 <!-- 实例工厂创建对象 -->
<!-- 因为工厂里面的方法不是静态的,所以工厂本身也得创建对象 -->
<bean id="bean3Factory" class="com.tyzr.bean.Bean3Factory"></bean>
<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>

测试类

 @Test
public void testBean3(){
//加载核心配置文件,创建对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//得到我们配置的对象
//<!-- 实例工厂创建对象 -->
//<!-- 因为工厂里面的方法不是静态的,所以工厂本身也得创建对象 -->
//<bean id="bean3Factory" class="com.tyzr.bean.Bean3Factory"></bean>
//<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>
Bean3 bean3 = (Bean3)context.getBean("bean3");
bean3.bean3();
}