Spring注入---静态工厂

在上一篇的博客中我们说Spring注入的一种方式---反射注入。今天我们继续来看一下Spring注入的另外的一种方式---静态的工厂

其实我们的注入,是利用到了配置的文件,当然这种方式的注入有优点也有缺点,我们学习也仅仅是作为可以注入的方式来理解。

什么事静态的工厂:

       可以这样理解:我们创建了一个工厂,在这个工厂里面有很多的创建好的对象,我们需要做的是从工厂中将创建的对象取出来。

首先创建对象的实体类还是需要我们来创建的Person:

package com.wdg.domain;

public class Person {
	private String name;
	private int age;

	public Person() {
	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}

}

实体类创建好了之后,我们需要做的事情是创建一个工厂,在这个工厂里面创建很多实体类的对象:

package com.wdg.test;

import java.util.HashMap;
import java.util.Map;

import com.wdg.domain.Person;

public class PersonStaticFactory {

	private static Map<Integer, Person> map = new HashMap<Integer, Person>();

	static {
		map.put(1, new Person("Honda", 30));
		map.put(2, new Person("Audi", 44));
		map.put(3, new Person("BMW", 54));
	}

	public static Person getPerson(int id) {
		return map.get(id);
	}
}

工厂创建好了,我们要配置相关的配置文件,然后从配置文件中利用工厂的方法获取到实体类:

<?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.xsd">
  <bean id="bmwCar" class="com.wdg.test.PersonStaticFactory" factory-method="getPerson">
        <constructor-arg value="3"></constructor-arg>           
    </bean>

    <bean id="audiCar" class="com.wdg.test.PersonStaticFactory" factory-method="getPerson">
        <constructor-arg value="2"></constructor-arg>           
    </bean>
</beans>

我们可以看到的是工厂的方法是getPerson,并且参数是我们获取到第几个实体类,如何获取到实体类,和上一篇的方式是一样的:

    public static void main(String[] args) {
    	ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-beans.xml");
    	Person person = (Person) ctx.getBean("bmwCar");
    	System.out.println(person);
	}

运行输出:

Person [name=BMW, age=54]

上面就是我们静态工厂的一种获取到实体类的一种办法。如果感觉这篇文章还不错,就扫一下红包吧,看看你能赚多少:

                                                                                   

希望对你有所帮助!!

猜你喜欢

转载自blog.csdn.net/datouniao1/article/details/84891784