Spring实现bean的创建(静态工厂)

编程入门 行业动态 更新时间:2024-10-10 15:26:15

Spring实现bean的创建(<a href=https://www.elefans.com/category/jswz/34/1771395.html style=静态工厂)"/>

Spring实现bean的创建(静态工厂)

Bean相关配置

创建Bean对象的不同方式

  1. new 对象(反射)创建对象

  2. 工厂创建对象

    1. 静态工厂创建对象 (调用工厂类中的静态方法获取对象)

    2. 实例工厂创建对象 (先实例化工厂-创建工厂对象,再调用工厂对象中的普通方法)

自己使用工厂模式创建对象

public class Account {private Integer id;private String name;private Double balance;// get set toString省略...   
}
//对象工厂: 创建对象
//静态工厂: 不用创建对象,直接调用工厂类中的静态方法创建对象(访问的是静态方法)
//实例工厂: 需要创建工厂对象,再公共工厂对象调用方法创建对象(访问的是非静态方法)
public class AccountFactory {//非静态方法public Account getAccount(){return new Account();}//静态方法public static Account getAccountByStatic(){return new Account();}
}
@Test
public void testFactory(){//静态工厂创建对象Account account1 = AccountFactory.getAccountByStatic();//实例工厂创建对象AccountFactory accountFactory = new AccountFactory();Account account2 = accountFactory.getAccount();
}

Spring实现bean的创建

普通方式

<!--这种方式等同于直接new对象(底层使用反射创建-newInstance())-->
<bean id="accountDao" class="com.itheima.ioc.dao.impl.AccountDaoImpl"></bean>

静态工厂

<!--
class: 工厂类全路径
factory-method: 工厂类中的静态方法
-->
<bean id="account1" class="com.itheima.ioc.factory.AccountFactory" factory-method="getAccountByStatic"></bean>

       测试:

@Test
public void testSpringStaticFactory(){ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");Account account1 = (Account) applicationContext.getBean("account1");System.out.println(account1);
}

实例工厂

<!--工厂对象-->
<bean id="accountFactory" class="com.itheima.ioc.factory.AccountFactory"></bean>
<!--factory-bean: 指定工厂实例factory-method: 指定工厂中的非静态方法
-->
<bean id="account2" factory-bean="accountFactory" factory-method="getAccount"></bean>

        测试

@Test
public void testSpringFactory(){ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");Account account2 = (Account) applicationContext.getBean("account2");System.out.println(account2);
}

更多推荐

Spring实现bean的创建(静态工厂)

本文发布于:2024-03-05 09:46:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1711957.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   工厂   Spring   bean

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!