欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring中Bean对象创建的三种方式

程序员文章站 2022-05-23 19:44:14
...

Bean实例化的三种方式:

无参构造方法实例化
工厂静态方法实例化
工厂实例方法实例化

工厂静态方法实例化:

/**
 * @description: 工厂静态方法实例化
 * @Author C_Y_J
 * @create 2021-02-25 08:55
 **/
public class StaticFactory {
    public static IUserService getUserService() {
        return new UserServiceImpl();
    }
}

applicationContext.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">

    <bean id="userService" class="com.cyj.springioc3.factory.StaticFactory" factory-method="getUserService" ></bean>
</beans>

注意:
factory-method=“getUserService”
spring会根据全限类名找到getUserService方法来得到Bean对象

工厂实例方法实例化:

/**
 * @description:
 * @Author C_Y_J
 * @create 2021-02-25 09:04
 **/
public class DynamicFactory {
    public IUserService getUserService() {
        return new UserServiceImpl();
    }
}

applicationContext.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">

    <bean id="factory" class="com.cyj.springioc3.factory.DynamicFactory"></bean>
    <bean id="userService" factory-bean="factory" factory-method="getUserService"></bean>
</beans>

注意:
spring通过class="com.cyj.springioc3.factory.DynamicFactory"创建一个factory的Bean。
在通过factory-bean="factory"指定Factory工厂,factory-method="getUserService"指定工厂里面的getUserService方法来得到一个叫userService对象。

相关标签: spring spring 5