2014-05-09 19 views
0

我有一個彈簧3.2應用程序,其中基於配置文件中的註釋是如下:packagesToScan在Spring配置

@Configuration 
@EnableWebMvc 
@Profile("production") 
@ComponentScan(basePackages = {"com.mypackage"}) 
@PropertySource({"classpath:myproperty.properties"}) 
public class WebConfig extends WebMvcConfigurationSupport{ 

    @Override 
    protected void configureContentNegotiation(ContentNegotiationConfigurer configurer) {    configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useJaf(false) 
     .defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML) 
     .mediaType("json", MediaType.APPLICATION_JSON); 
    } 

    @Bean(name = "appProperty") 
    public static PropertySourcesPlaceholderConfigurer appProperty() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    } 
} 

我想給一定的靈活性,這恰恰意味着該應用程序的用戶可以開發彈簧組件並將其打包到jar中(包名可以是任何內容,但所有組件類都可以從我的應用程序中擴展一個類)。我想了解如何使新組件的發現可行?用戶絕對不能改變我的應用程序代碼中的任何內容,他可以訪問web.xml並且可能只是一個屬性文件。

我需要一種方法來讀取提供的軟件包名稱,然後調用應用程序上下文中的組件掃描。任何幫助真的很感激。

謝謝。

+0

似乎類似於我提出這樣的問題:HTTP:// stackoverflow.com/questions/23437936/dangers-of-componentscaning-all-packages-with-filters – CodeChimp

+0

嘿謝謝你指出,你有沒有找到任何可接受的解決方案? – dharam

+0

好吧,我有一個解決方案:我使用過濾器並從'**'掃描整個類路徑,但是我沒有發現任何告訴我的東西,我要麼完全沒有意義,要麼完全輝煌。但這是一個選擇。在我的情況下,我使用基於'@ Controller'的元註釋來過濾(僅爲我的元註釋掃描),但您可以使用接口或抽象類並對其進行過濾。 – CodeChimp

回答

0

我發現了另一個適合我的解決方案,寫在這裏面向可能面臨同樣問題的其他人。

假設我想插入名爲TestExtractorFactory的新組件。然後我們需要編寫兩個類,一個是註釋@Configuration,而這個組件是一個簡單的POJO(不是一個彈簧組件)。

下面是兩類:

package com.test.extractor; 

import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 

@Configuration 
public class TestConfig { 

    @Bean(name="testExtractorFactory") 
    public TestExtractorFactory testExtractorFactory(){ 
     return new TestExtractorFactory(); 
    } 
} 

,這裏是實際的組件:

package com.test.extractor; 
public class TestExtractorFactory extends ExtractorFactory{ 

    public TestExtractorFactory() { 
     super("TESTEX"); 
    } 

    // write other methods you want and your framework requires. 

} 

不用擔心什麼了ExtractorFactory是。新組件是從ExtractorFactory

擴展如何使它能夠爲@ComponentScan我們只是需要將其添加到我們的web.xml如下:

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>com.framework.config.WebConfig, 
     com.test.extractor.TestConfig 
    </param-value> 
</context-param>