2013-04-04 44 views
3

我有以下控制器定義:用SpringMVC:變量在註釋

@Controller 
@RequestMapping("/test") 
public class MyController extends AbstractController 
{ 

    @Autowired 
    public MyController(@Qualifier("anotherController") AnotherController anotherController)) 
    { 
    ... 
    } 

} 

我不知道是否有可能在@Qualifier註解使用變量,這樣我可以注入不同的.properties文件不同的控制器如:

@Controller 
@RequestMapping("/test") 
public class MyController extends AbstractController 
{ 

    @Autowired 
    public MyController(@Qualifier("${awesomeController}") AnotherController anotherController)) 
    { 
    ... 
    } 

} 

每當我嘗試,我得到:

org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No matching bean of type [com.example.MyController] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this 
dependency. Dependency annotations: 
{@org.springframework.beans.factory.annotation.Qualifier(value=${awesomeController}) 

我已經包括d我的config.xml文件下面bean:

<bean id="propertyConfigurer" 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="locations"> 
     <list> 
      <value>classpath:config/application.properties</value> 
     </list> 
    </property> 
</bean> 

但豆不起作用,除非我在XML文件中顯式聲明的bean。

我該怎麼做註釋?

+0

http://stackoverflow.com/questions/317687/how-can-i-inject-a-property-value-into-a-spring-bean-which-was-configured-using和http:// springinpractice 。COM/2008/12/02 /新的東西,在彈簧-30/ – NimChimpsky 2013-04-04 16:02:00

回答

2

首先,我認爲依賴注入依賴於配置屬性是不好的做法。試圖做到這一點你可能會走錯方向。

但是要回答您的問題:訪問placeHolder屬性需要依賴注入完成。爲了確保它,您可以將您的代碼訪問@PostContruct帶註釋的方法中的屬性。

您將需要使用getBean()方法手動從applicationContext中檢索bean。

@Value("${awesomeController}") 
private String myControllerName; 

@PostConstruct 
public void init(){ 
    AnotherController myController = (AnotherController) appContext.getBean(myControllerName); 
} 
+0

我試圖@ PostContruct的構造,但是這是一個無效的批註的位置,所以我創建了一個setter方法: @ PostConstruct @自動裝配Autowired 公共無效集( @預選賽( 「$ {} awesomeController」)anotherController anotherController) { ... } 但我發現了以下錯誤: java.lang.IllegalStateException:生命週期方法註釋需要一個沒有-arg方法 你能詳細解釋一下嗎? – Jason 2013-04-04 13:50:58

+0

我編輯了我的答案來展示一個例子。 – kgautron 2013-04-04 13:57:04

1

我不知道你在做什麼是可能的,但我可以提出一個稍微不同的方法,但前提是你使用Spring 3.1+。你可以嘗試使用Spring Profiles。

定義要在不同的控制器,每個配置文件之一:

<beans> 
    <!-- Common bean definitions etc... --> 

    <beans profile="a"> 
     <bean id="anotherController" class="...AnotherController" /> 
    </beans> 

    <beans profile="b"> 
     <!-- Some other class/config here... --> 
     <bean id="anotherController" class="...AnotherController"/> 
    </beans> 
</beans> 

您的控制器將失去@Qualifier,成爲類似:

@Autowired 
public MyController(AnotherController anotherController) { 
    ... 
} 

然後在運行時,你可以指定哪些控制器豆你想要通過使用系統屬性激活相應的配置文件來使用,例如:

-Dspring.profiles.active="a" 

或:

-Dspring.profiles.active="b" 

它可能會設定一個基於屬性文件的配置文件,但你可以從this post在春季博客找到更多關於Spring配置文件。我希望這有所幫助。