Frage

I have a spring 3.2 application where the Annotation based Config file is as below:

@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();
    }
}

I am trying to give some flexibility, which precisely means user of this application can develop a spring component and package it in a jar (the package name can be anything, but all the component classes extend a class from my application). I want to understand how do I make the discovery of the new component feasible? The user definitely cannot change anything in my application code, he has access to the web.xml and may be a properties file only.

I need a way to read the supplied package name and then invoke the component scan on the application context. Any help is really appreciated.

Thanks.

War es hilfreich?

Lösung

I found another solution which suits me, writing here for others who might be facing the same problem.

Assume I want to plug in the new component named TestExtractorFactory. Then we need to write two classes, one with an annotation @Configuration and the component being a simple POJO (not a spring component).

Below are the two classes:

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();
    }
}

and here is the actual component:

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

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

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

}

Need not worry about what an ExtractorFactory is. The new component is extended from an ExtractorFactory

How to make it enable for a @ComponentScan we just need to add it in our web.xml as below:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.framework.config.WebConfig,
         com.test.extractor.TestConfig
    </param-value>
</context-param>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top