【Spring 系列】二、spring三种实例化bean的方式

  • beans.xml中配置

    <!-- 三种实例化bean的方式 -->
    
     <!-- 1.使用类构造器实例化 -->
    <bean id="personService" class="com.liuyong666.service.impl.PersonServiceBean"></bean>
    
    <!-- 2.使用静态工厂方法实例化 -->
    <bean id="personService2" class="com.liuyong666.service.impl.PersonServiceBeanFactory" factory-method="createPersonServiceBean"></bean>
    
    <!-- 3.使用实例工厂方法实例化 -->
    <bean id="personServiceFactory" class="com.liuyong666.service.impl.PersonServiceBeanFactory"></bean>
    <bean id="personService3" factory-bean="personServiceFactory" factory-method="createPersonServiceBean2"></bean>
    
  • PersonServiceBeanFactory类

    package com.liuyong666.service.impl;
    public class PersonServiceBeanFactory {
         
    	
    	public static PersonServiceBean createPersonServiceBean(){
         
    		return new PersonServiceBean();
    	}
    	
    	public PersonServiceBean createPersonServiceBean2(){
         
    		return new PersonServiceBean();
    	}
    }
    
  • 测试类

  public class TestSpring {
   /** ​ * 使用spring框架获取bean ​ */@Testpublic void getBeanBySpring(){
   
  ​			ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{
   "beans.xml"});
  ​			PersonService bean = (PersonService) context.getBean("personService");
  ​			bean.save();}/** ​ * 使用静态工厂方法获取bean ​ */@Testpublic void getBeanByStaticFactory(){
   
  ​			ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{
   "beans.xml"});
  ​			PersonService bean = (PersonService) context.getBean("personService2");
  ​			bean.save();}/** * 使用实例工厂方法获取bean */
  	@Test
  	public void getBeanByInstantceFactory(){
   
  		ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{
   "beans.xml"});
  		PersonService bean = (PersonService) context.getBean("personService3");
  		bean.save();
  	}
  
  }

全部评论

相关推荐

小红书 后端开发 总包n+8w+期权
点赞 评论 收藏
分享
牛客868257804号:九个中铁八个中建
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务