传智播客Spring2.5视频教程_Spring的三种实例化Bean的方式 1

这节课 很短,8分钟左右。但是,丛开始我的疑问就一直没有解决:三种方法的应用场合是什么? 差别在那里? 老师只是说 通过构造方法实例化 占大多数。,我查一下,看看有什么说法?

1 构造函数

2 静态工厂

3 实例工厂

 

配置文件"/three/threebeans.xml"

           <!--1 -->
           <bean id="personService" class="three.spring.service.impl.PersonServiceBean"></bean>

 

           <!--2 -->
           <bean id="personService2" class="three.spring.service.impl.PersonServiceBeanStaticFaction"
           factory-method="getPersonService"></bean>
          
           <!--3 -->
           <bean id="personServiceBeanFaction" class="three.spring.service.impl.PersonServiceBeanFaction"></bean>
           <bean id = "personService3" factory-bean="personServiceBeanFaction" factory-method="getPersonService"></bean>

 

///

package three.spring.junit;


import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import two.spring.service.PersonService;


public class SpringTest {

 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
 }
 @Test
 public void instanceSpring()  {
  
  // 在类路径下,寻找配置文件,实例化spring容器。
  ApplicationContext ctx = new ClassPathXmlApplicationContext("/three/threebeans.xml");
  
  
  //配置文件中bean的id,推荐首字母小写
  PersonService personService = (PersonService)ctx.getBean("personService3");
  
  personService.savePerson();
 }

}

package three.spring.service;

public interface PersonService {

 //面向接口编程,降低耦合度
 public abstract void savePerson();

package three.spring.service.impl;

import two.spring.service.PersonService;

//1 构造函数
public class PersonServiceBean implements PersonService {

  
 public void savePerson() {
  System.out.println("我是包[two.spring.service.impl]的" +"类[PersonService]的[savePerson]方法");
  
 }
}

package three.spring.service.impl;

//3 实例工厂
public class PersonServiceBeanFaction {
 
 public PersonServiceBean getPersonService(){
  return new PersonServiceBean();  
 }
}

package three.spring.service.impl;

//2 静态工厂
public class PersonServiceBeanStaticFaction {
 
 public static PersonServiceBean getPersonService(){
  return new PersonServiceBean();  
 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值