2 spring配置bean的三种方式

1.service接口

package spring.service;

public interface Service {
    public void do_some();
}

2.实现类

package spring.service;

public class ServiceImp  implements Service{
    @Override
    public void do_some() {
        System.out.println("你好,spring");
    }
}

3.静态工厂

package spring.service;

public class Service_fatory1 {
    public static ServiceImp getService(){
        return new ServiceImp();
    }
}

4.实例工厂

package spring.service;

public class Service_fatory2 {
    public ServiceImp getService(){
        return new ServiceImp();
    }
}

4。bean.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <!--装配bean的三种方式-->
    <!--第一种,普通方式-->
    <bean id="service" class="spring.service.ServiceImp"></bean>
    <!--第二种,静态工厂-->
    <bean id="service2" class="spring.service.Service_fatory1" factory-method="getService"></bean>
    <!--第三种方式,实例工厂-->
    <!--首先创造工厂bean-->
    <bean id="fatory2" class="spring.service.Service_fatory2"></bean>
    <!--创建一个索引去调用实例方法-->
    <bean id="service3" factory-bean="fatory2" factory-method="getService"></bean>
</beans>

5.测试类

package spring.test;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring.service.Service;

public class test {
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Service service= (Service) context.getBean("service");
        Service service1= (Service) context.getBean("service2");
        Service service2= (Service) context.getBean("service3");
        service.do_some();
        service1.do_some();
        service2.do_some();
    }
}

6.结果完美
7.感想
(1)不要害怕报错,努力去读logging
(2)事实上就是复习了工厂模式罢了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值