spring bean的三种实例化方式 (xml方式)

时间:2022-12-18 19:05:56
  • 1,类中的无参构造函数创建对象(最常用的方式)
    spring配置文件
<bean id = "person" class="com.wjk.spring.test.beans.xml.Person"/>

java类文件

public class Person {
    public void sys() {
        System.out.println("com.wjk.spring.test.beans.xml.Person:sys");
    }
}

测试类的测试方法

public void SpringBeansTestFactory() {
        ApplicationContext beans = new ClassPathXmlApplicationContext("spring_context_test.xml");  
        Person person = (Person) beans.getBean("person");
        person.sys();
}
  • 2,静态工厂创建对象 (创建静态的方法,返回类对象)
    静态工厂类
public class SpringBeanStaticFactory {
    public static Person getPerson() {
        return new Person();
    }
}

spring 配置文件bean的配置

<bean id = "staticPersonFactory" class="com.wjk.spring.test.beans.xml.SpringBeanStaticFactory" factory-method="getPerson"/>

测试类中的测试方法

public void SpringBeansTestFactory() {
        ApplicationContext beans = new ClassPathXmlApplicationContext("spring_context_test.xml");  
        Person staticPersonFactory= (Person) beans.getBean("staticPersonFactory");
        staticPersonFactory.sys();
}
  • 3,默认的无参构造函数 (创建不是静态的方法,返回类对象)
    spring 配置文件
<bean id = "personFactory" class="com.wjk.spring.test.beans.xml.SpringBeanFactory"/>
    <bean id = "person1" factory-bean="personFactory" factory-method="getPerson"/>
实例工厂类文件
public class SpringBeanFactory {
    public Person getPerson() {
        return new Person();
    }
}

测试类

public void SpringBeansTestFactory() {
        ApplicationContext beans = new ClassPathXmlApplicationContext("spring_context_test.xml");  
        Person person1 = (Person) beans.getBean("person1");
        person1.sys();
    }’