Exclude subpackages from Spring autowiring?

后端 未结 9 768
傲寒
傲寒 2020-12-02 10:00

Is there a simple way to exclude a package / sub-package from autowiring in Spring 3.1?

E.g., if I wanted to include a component scan with a base package of co

相关标签:
9条回答
  • 2020-12-02 10:57

    One thing that seems to work for me is this:

    @ComponentScan(basePackageClasses = {SomeTypeInYourPackage.class}, resourcePattern = "*.class")
    

    Or in XML:

    <context:component-scan base-package="com.example" resource-pattern="*.class"/>
    

    This overrides the default resourcePattern which is "**/*.class".

    This would seem like the most type-safe way to ONLY include your base package since that resourcePattern would always be the same and relative to your base package.

    0 讨论(0)
  • 2020-12-02 10:57

    You can also include specific package and excludes them like :

    Include and exclude (both)

     @SpringBootApplication
            (
                    scanBasePackages = {
                            "com.package1",
                            "com.package2"
                    },
                    exclude = {org.springframework.boot.sample.class}
            )
    

    JUST Exclude

    @SpringBootApplication(exclude= {com.package1.class})
    public class MySpringConfiguration {}
    
    0 讨论(0)
  • 2020-12-02 11:07

    I am using @ComponentScan as follows for the same use case. This is the same as BenSchro10's XML answer but this uses annotations. Both use a filter with type=AspectJ

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
    import org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration;
    import org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration;
    import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.FilterType;
    import org.springframework.context.annotation.ImportResource;
    
    @SpringBootApplication
    @EnableAutoConfiguration
    @ComponentScan(basePackages = { "com.example" },
        excludeFilters = @ComponentScan.Filter(type = FilterType.ASPECTJ, pattern = "com.example.ignore.*"))
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
    0 讨论(0)
提交回复
热议问题