Tuesday, October 5, 2010

Spring v3.0.2 Learning Note 3 - Initialisation of Beans

  • 使用类的构造器实例化
<bean id="personService" class="com.spring.test.manager.impl.PersonManager"/>
  • 使用静态工厂的方法实例化
假设有一个工厂类返回类的实例。
package com.spring.test.manager.impl;

public class PersonManagerFactory {
    // 静态工厂方法创建类的实例
    public static PersonManager createPersonManager() {
        return new PersonManager();
    }
}

 这种情况下该如何配置spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="personService" class="com.spring.test.manager.impl.PersonManager" />
    <bean id="personService2" class="com.spring.test.manager.impl.PersonManagerFactory"
        factory-method="createPersonManager" />
</beans>

创建junit测试
package com.spring.test.junit;

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

import com.spring.test.manager.IPersonService;

public class PersonServiceTest {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "spring.xml");
        IPersonService personService = (IPersonService) ctx
                .getBean("personService2");
        personService.save();

    }

}
  • 使用实例工厂方法实例化
与上面的区别是工厂方法不是static.

假设工厂类为:
package com.spring.test.manager.impl;

public class PersonManagerFactory {

    public static PersonManager createPersonManager() {
        return new PersonManager();
    }
    // 注意这个工厂方法不是静态的,与上面的方法不同
    public PersonManager createPersonManager2() {
        return new PersonManager();
    }
}


注意配置文件的红色部分
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="personService" class="com.spring.test.manager.impl.PersonManager" />
    <bean id="personService2" class="com.spring.test.manager.impl.PersonManagerFactory"
        factory-method="createPersonManager" />
    <bean id="personServiceFactory" class="com.spring.test.manager.impl.PersonManagerFactory" />
    <bean id="personService3" factory-bean="personServiceFactory"
        factory-method="createPersonManager2" />
</beans>

创建junit测试类测试可得正确结果。

No comments:

Post a Comment