2013-05-30 28 views
3

我正在嘗試創建一個應該根據運行時參數創建其他(原型)bean的@Configuration工廠bean。我想使用基於spring的基於java的配置,但不知何故我無法使它工作。如何使用@Bean方法根據運行時參數提供不同的bean

下面是一個例子:

enum PetType{CAT,DOG;} 

abstract class Pet {  
} 

@Component 
@Scope("prototype") 
class Cat extends Pet{ 
} 

@Component 
@Scope("prototype") 
class dog extends Pet{ 
} 

@Configuration 
public class PetFactory{  
    @Bean 
    @Scope("prototype") 
    public Pet pet(PetType type){ 
     if(type == CAT){ 
      return new Cat(); 
     }else 
      return new Dog(); 
    } 
} 

petFactory.animal(PetType.CAT); 

我查春文檔和這裏要求所有相關問題,但我所創建的豆供應運行參數的情況下結束。我需要向工廠提供運行時參數,這些參數必須使用它們來創建不同的bean。

編輯: 似乎(目前)沒有辦法來定義一個參數到@Bean註解的方法如 「運行時」。 Spring假定方法參數將被用作新bean的構造器參數,因此它試圖用容器管理的bean來滿足這種依賴性。

+0

查看配置文件。 「PetType」從哪裏來? –

+0

PetType來自用戶輸入。 – Max

+0

如果它來自用戶輸入,爲什麼你需要利用Spring創建它們(你正在調用新的,所以Spring不會管理它們)?讓工廠成爲一個彈簧組件,但有其他的東西驅動PetType的創建 - 可以在您的攔截器,控制器或任何地方。 – Scott

回答

1

嘗試使用@Configurable:

class Factory { 

    Pet newPetOfType(PetType type) { 
     switch (type) { 
      case CAT: return new Cat(); 
      ... 
     } 
    } 

    @Configurable 
    private static class Cat extends Pet { 
     @Autowired private Prop prop; 
     ... 
    } 
} 
+0

這似乎很有趣,但需要AspectJ編織,我需要明確啓用。目前我只使用Spring AOP作爲事務代理。 – Max

2

這看起來好像可以很好地利用Spring Profiles功能。在這裏你可以閱讀約Java configurations,這裏約XML Profiles

你的個人資料會定義一個Pet bean。然後,您的工廠可以連接該豆。

要修改您使用的配置文件,只需添加:-Dspring.profiles.active = dog或-Dspring.profiles.active = cat(或任何其他名稱)。

+0

這是可能的,但是是一種「靜態」的方式。我需要在需要時動態創建貓和狗。 – Max

0

你可以只@Autowire您PetFactory豆成所需要的bean並調用動物()方法在運行時所需的類型,如以下方法:

@Configuration  
public class AppConfiguration { 

    @Bean 
    @Scope("prototype") 
    public Pet getPet(PetType type) { 

     if(type == CAT){ 
      return new Cat(); 
     } else 
      return new Dog(); 
    } 

} 

//... 
// Then in required class 
@Service 
public class PetService { 

    @Autowired 
    private AppConfiguration configuration; 

    //..... 

    public Pet getPetByType(PetType type) { 
     return configuration.getPet(type); 
    } 

} 
相關問題