[英]Dependency Injection, need factory like functionality
我正在使用Spring開發Web應用程序。
我有一個通用的抽象類及其許多實現。
現在,在控制器中,根據某些參數,我需要它的不同實現。
這可以通過工廠模式輕松實現。
例如:
abstract class Animal{
public abstract void run(){
}
}
class Dog extends Animal{
...
}
Class Cat extends Animal{
...
}
現在使用工廠模式,我可以使用工廠方法創建工廠類,該方法基於某些參數創建動物。 但是我不想自己創建實例 。
我需要相同的功能,但我希望Spring可以管理所有東西。 因為不同的實現都有它們的依賴關系,所以我希望它們由Spring注入。
處理這種情況的最佳方法是什么?
@Component
public class AnimalFactory {
@Autowired
private Dog dog;
@Autowired
private Cat cat;
public Animal create(String kind) {
if (king.equals("dog") {
return dog;
}
else {
return cat;
}
}
}
@Component
public class Cat extends Animal {
...
}
@Component
public class Dog extends Animal {
...
}
@Component
private class Client {
@Autowired
private AnimalFactory factory;
public void foo() {
Animal animal = factory.create("dog");
animal.run();
}
}
將要創建的bean配置為原型bean。 接下來創建一個工廠,該工廠基本上根據輸入知道從應用程序上下文中檢索哪個bean(因此,基本上不讓它們創建,而是讓spring做繁重的工作)。
可以使用與@Scope("prototype")
@Component
或使用XML配置來完成組件的定義。
abstract class Animal{
public abstract void run(){}
}
@Component
@Scope("prototype")
class Dog extends Animal{}
@Component
@Scope("prototype")
Class Cat extends Animal{}
並用AnimalFactory
完成答案。
@Component
public class AnimalFactory implements BeanFactoryAware {
private BeanFactory factory;
public Animal create(String input) {
if ("cat".equals(input) ) {
return factory.getBean(Cat.class);
} else if ("dog".equals(input) ) {
return factory.getBean(Dog.class);
}
}
public void setBeanFactory(BeanFactory beanFactory) {
this.factory=beanFactory;
}
}
除了JB的答案,您還可以使用基於XML的配置。 以下內容也將起作用:
package com.example;
class PetOwner(){
private Animal animal;
public PetOwner() {
};
public void setAnimal(Animal animal) {
this.animal = animal;
}
}
使用以下xml-config:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="petOwner" class="com.example.PetOwner">
<property name="animal" ref="animal" />
</bean>
<bean id="animal" class="com.example.pets.Dog" scope="prototype" />
每次請求對象時,prototype-scope都會返回一個新實例。 參見http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.