2014-05-09 22 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>