Spring系列教程——04三种Bean装配方式讲解

Spring系列教程——04三种Bean装配方式讲解

Bean装配即在beans.xml文件里面配置bean标签。
上一篇:Spring系列教程——03Spring容器的创建

下一篇:Spring系列教程——05Bean的生命周期与作用域

1.通过new来创建

<bean id="UserDao" class="Impl.UserDaoImpl"></bean>

这个方式前面的章节我们已经用过了,这里不做演示。

2.静态工厂的方式

创建静态工厂类

package Factory;
import Impl.UserDaoImpl;
import dao.UserDao;
public class UserDaoFactory {
    public static UserDaoImpl getUserDaoImpl(){
        return new UserDaoImpl();
    } 
}

在beans.xml文件中配置下面内容:

<bean id="factory" class="Factory.UserDaoFactory" factory-method="getUserDaoImpl"></bean>

这个配置表示调用UserDaoFactory的getUserDaoImpl方法(注意这里的方法必须是静态的)。
测试代码如下:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserDaoImpl userDaoImpl = (UserDaoImpl) context.getBean("Factory");

在这里插入图片描述

3.实例化工厂的方式

将静态方法改为非静态如下:

public  UserDaoImpl getUserDaoImpl(){
    return new UserDaoImpl();
}

beans.xml文件对应配置如下:

<bean id="factory" class="Factory.UserDaoFactory" ></bean>
<bean id="UserDaoImpl" factory-bean="factory" factory-method="getUserDaoImpl"></bean>

测试代码:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserDaoImpl userDaoImpl = (UserDaoImpl) context.getBean("UserDaoImpl");

在这里插入图片描述
上一篇:Spring系列教程——03Spring容器的创建
下一篇:Spring系列教程——05Bean的生命周期与作用域

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值