Sprgin IOC容器Bean实例化的三种方式

本文详细介绍了SpringIOC容器中Bean实例化的三种方式:构造器实例化、静态工厂实例化以及较少使用的实例化工厂实例化。在构造器实例化中,Spring通过bean的默认构造函数创建对象;静态工厂实例化则允许用户自定义静态工厂方法来创建Bean,提供了更多的灵活性。每种方式都有其应用场景,通常开发中常用的是构造器实例化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3. Sprgin IOC容器Bean实例化的三种方式

构造器实例化:

第一步:设置配置文件spring.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
    https://www.springframework.org/schema/beans/spring-beans.xsd">
  <bean id="userService" class="com.xxxx.service.UserService"></bean>
</beans>

第二步:

ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
UserService userService = (UserService) ac.getBean("userService"); 
userService.test();

在这种方法中,是通过bean的缺省构造函数创建,所以缺省的构造函数必须存在,否则则会出现错误。


静态工厂实例化:

第一步:定义静态工厂类:

package com.xxxx.factory;
import com.xxxx.service.UserService;
/**
* 定义静态工厂类
*/
public class StaticFactory {
  /**
  * 定义对应的静态方法,返回实例化对象
  * @return
  */
  public static UserService createUserService() {
    return new UserService();
 }
}

第二步:设置配置文件spring.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
    https://www.springframework.org/schema/beans/spring-beans.xsd">
  <!--静态工厂-->
  <bean id="userService" class="com.xxxx.factory.StaticFactory" factory-
method="createUserService"></bean>
</beans>

第三步:获取实例化对象:

ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
UserService userService = (UserService) ac.getBean("userService"); 
userService.test();

当我们指定Spring使用静态工厂方法来创建Bean实例时,Spring将先解析配置文件,并根据配置文件指定的信息,通过反射调用静态工厂类的静态工厂方法,并将该静态工厂方法的返回值作为Bean实例,在这个过程中,Spring不再负责创建Bean实例,Bean实例是由用户提供的静态工厂方法提供的。

通过这种方法,可以在初始化bean对象时对此进行额外的操作。


第三种方法:实例化工厂实例化:

这种不做介绍,用的比较少。

开发中项目一般使用一种方式实例化bean,项目开发基本采用第一种方式,交给Spring托管,使用时直接拿来使用即可。另外两种了解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值