2013-02-14 31 views
5

這裏是我現在所擁有的工作正常在一個singleton bean生成原型對象用。它所做的是一個市場類返回項目對象的數組:HOWTO使用的Spring Java配置

我有類市場

class market { 

    public ArrayList<Items> createItems(HashMap<String,String> map) { 
     ArrayList<Items> array = new ArrayList<Items>(); 
     for (Map.Entry<String, String> m : map.entrySet()) { 
      Item item = new Item(); 
      item.setName(m.key()); 
      item.setValue(m.value()); 
      array.add(item); 
     } 
     return array; 
    } 
} 

類項目的簡單類的getter和setter的名稱和值

這裏是如何我的配置文件如下:

@Configuration 
public class MarketConfig { 

    @Bean 
    public Market market() { 
     return new Market(); 
    } 
} 

我如何想改變我的代碼:(原因:我不想

Item item = new Item(); 

在隨後方法。我希望春將它注入市場)我知道原型範圍將給我新的bean每次我打電話item(); 現在我想爲createItems方法的for循環中的每個迭代創建新的bean。我怎麼告訴春天給我。我知道

一種方式是做

applicationContext context = new AnnotationConfigApplicationContext(); 
context.getBean(Item.class); 

但是有沒有讓我的工作做任何其他方式。 感謝

回答

19

是的,你可以使用查找方法

public abstract class ItemFactory { 

    public abstract Item createItem(); 

} 
現在

在applicationContext.xml中只是把下面的按需創建原型方法:

<bean id="item" class="x.y.z.Item" scope="prototype" lazy-init="true"/> 

和配置工廠:

<bean id="itemFactory" class="x.y.z.ItemFactory"> 
<lookup-method name="createItem" bean="item"/> 
</bean> 

現在,所有你需要爲了用它做的是Autow IRE任何bean中:

,並呼籲YOUT查找方法:

@Service 
public class MyService{ 

    @Autowired 
    ItemFactory itemFactory; 

    public someMethod(){ 
     Item item = itemFactrory.createItem(); 
    } 

} 
每次調用時

createItem()您將收到參考Item類的新創建的實例。

P.S.:我看到您使用的是@Configuration而不是xml,您需要檢查是否可以在配置Bean內部配置查找方法。

希望它有幫助。

更新:訣竅很簡單:

@Configuration 
public class BeanConfig { 

    @Bean 
    @Scope(value="prototype") 
    public Item item(){ 
     return new Item(); 
    } 


    @Bean 
    public ItemManager itemManager(){ 
     return new ItemManager() { 

      @Override 
      public Item createItem() { 
       return item(); 
      } 
     }; 
    } 
} 
+0

我會看看是否有人可以使用@configuration來給出解決方案。否則我會接受它。我將在網上查詢如何使用基於java的彈簧配置查找方法 – javaMan 2013-02-14 19:04:16

+1

@ravi,請看我的更新訣竅是簡單的:) – 2013-02-14 19:58:10

+0

謝謝剛纔我發現這個鏈接。我在這裏找到了類似的解http://static.springsource.org/spring/docs/3.0.0.RC3/reference/html/ch03s11.html。 – javaMan 2013-02-14 20:46:53

4

它可以,如果你使用的是Java 8

@Configuration 
public class Config { 

    @Bean 
    @Scope(value = "prototype") 
    public Item item() { 
     return new Item(); 
    } 

    @Bean 
    public Supplier<Item> itemSupplier() { 
     return this::item; 
    } 
} 

,並簡化後,你可以在你的市場類使用該供應商創建原型項目bean。

@Component 
public class Market { 

    private final Supplier<Item> itemSupplier; 

    @Autowired 
    public Market(Supplier<Item> itemSupplier) { 
     this.itemSupplier = itemSupplier; 
    } 

    private Item createItem() { 
     return itemSupplier.get(); 
    } 

} 

非常簡單,並且不需要額外的工廠bean或接口。

相關問題