Spring创建bean的三种方式

Spring创建bean的三种方式

1、使用默认构造函数创建

在Spring的配置文件中使用bean标签,配置id和class属性,没有其他属性和标签时,如果类中没有默认构造函数,对象无法创建

public static void main(String[] args) {
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    IAccountService as = (IAccountService)ac.getBean("accountService");
    System.out.println("as = " + as);
    as.saveAccount();
}
public class AccountServiceImpl implements IAccountService {
    public AccountServiceImpl() {
        System.out.println("Class AccountServiceImpl AccountServiceImpl method");
    }
    public void saveAccount() {
        System.out.println("Class AccountServiceImpl saveAccount method");
    }
}
<bean id="accountService" class="cn.wuvvu.service.impl.AccountServiceImpl" />
2、 使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,然后存入Spring容器)
<bean id="instanceFactory" class="cn.wuvvu.factory.InstaceFactory" />
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService" />
/**
 * 模拟一个工厂类,无法通过修改源码的方式来提供默认构造函数(假如这是个在jar包中的类)
 */
public class InstaceFactory {
    public IAccountService getAccountService() {
        return new AccountServiceImpl();
    }
}
3、使用工厂中的静态方法创建对象(使用某个类的静态方法创建对象,然后存入Spring容器)
<bean id="accountService" class="cn.wuvvu.factory.StaticFactory" factory-method="getAccountService" />
public class StaticFactory {
    public static IAccountService getAccountService() {
        return new AccountServiceImpl();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值