Spring 装配bean的三种方式

spring 是一种容器框架在xml文件中装配bean的方式主要有下面三种

拿userService举个例子

一  直接通过 new实现类来实现

 在beans.xml中配置的bean

 <bean id="userService" class="com.lilang.service.UserServiceImpl"></bean>

写个接口,实现类大致如下图

具体代码如下

package com.lilang.service;

public interface IUserService {
    public void add();
}

实现类 UserServiceImpl

package com.lilang.service;

public class UserServiceImpl implements IUserService {


    private String name;

    @Override
    public void add() {
        System.out.println("创建成功"+name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name =name;
    }
}

在测试中首先通过 ApplicationContext进行连接初始化然后通过context.getBean通过id获得对象。

具体代码如下

package com.lilang.test;
import com.lilang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

    class DemoTestTest {

    @org.junit.jupiter.api.Test
    void test01() {
      ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml") ;

      UserServiceImpl userService= (UserServiceImpl) context.getBean("userService");

      userService.add();

    }
}

运行出来结果

至于为什么会出现null是因为没有进行property注入。

第二种通过静态工厂的方法

<!-- 第二种方式:通过静态工厂方法

  -->
 <bean id="userService2" class="com.lilang.service.UserSereviceFactory1" factory-method="createUserService"></bean>

需要注意版本问题可能会出现版本不匹配的问题

类中多写一个工厂类类中有个创建userservice的方法其他的大致通第一个,如图


第三种方法:实例工厂方法

直接通过以下两个方法进行加载

factory-bean="factory2" factory-method="createUserService"

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值