其他分享
首页 > 其他分享> > spring中使用工厂类创建bean对象的过程

spring中使用工厂类创建bean对象的过程

作者:互联网

静态方法时
xml文件
<bean name="fs"
        class="com.qq.pojo.StudentFactory"
          factory-method="produce"></bean>
          
         中间类
         
         package com.qq.pojo;

public class StudentFactory {
    public static Student produce(){
        return new Student("小名",10,19);
    }
}

实现类
@Test
    public  void test5(){
        //<!--scope 设置是单例还是非单例-->
        //scope="prototype" 表示多例模式
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");

        Student s1 = (Student) context.getBean("fs");
        /*Student bean1 = context.getBean(Student.class);
        System.out.println(bean==bean1);
        System.out.println(bean);
        System.out.println(bean1);*/
        System.out.println(s1);
    }
    
    
    非静态方法
    
    
    <bean id="maker" class="com.qq.pojo.StudenetMaker"></bean>
    <bean name="ms" factory-bean="maker" factory-method="make"></bean>
    
    工厂类
class StudenetMaker{
    public  Student make(){
        return new Student("tom",10,19);
    }
}
测试类
 public  void test6(){
        //<!--scope 设置是单例还是非单例-->
        //scope="prototype" 表示多例模式
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");

        Student s1 = (Student) context.getBean("ms");
        /*Student bean1 = context.getBean(Student.class);
        System.out.println(bean==bean1);
        System.out.println(bean);
        System.out.println(bean1);*/
        System.out.println(s1);
    }

标签:context,spring,System,bean1,bean,Student,创建,println,out
来源: https://www.cnblogs.com/koushijun575/p/16521339.html