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);
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值