1. 程式人生 > >spring bean的三種例項化方式 (xml方式)

spring bean的三種例項化方式 (xml方式)

  • 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();
    }’