IT박스

Spring autowiring에서 하위 패키지를 제외 하시겠습니까?

itboxs 2020. 10. 23. 07:43
반응형

Spring autowiring에서 하위 패키지를 제외 하시겠습니까?


Spring 3.1의 autowiring에서 패키지 / 하위 패키지를 제외하는 간단한 방법이 있습니까?

예를 들어, 기본 패키지와 함께 구성 요소 스캔을 포함하려는 경우 com.example제외하는 간단한 방법이 com.example.ignore있습니까?

(왜? 통합 테스트에서 일부 구성 요소를 제외하고 싶습니다.)


<exclude-filter>를 사용하여 명시 적으로 패키지를 제외 할 수 있는지 확실하지 않지만 정규식 필터를 사용하면 효과적으로 얻을 수 있습니다.

 <context:component-scan base-package="com.example">
    <context:exclude-filter type="regex" expression="com\.example\.ignore\..*"/>
 </context:component-scan>

주석 기반으로 만들려면 통합 테스트에서 제외하려는 각 클래스에 @ com.example.annotation.ExcludedFromITests와 같은 주석을 달아야합니다. 그런 다음 구성 요소 스캔은 다음과 같습니다.

 <context:component-scan base-package="com.example">
    <context:exclude-filter type="annotation" expression="com.example.annotation.ExcludedFromITests"/>
 </context:component-scan>

이제 소스 코드 자체에 클래스가 통합 테스트를위한 애플리케이션 컨텍스트에 포함되지 않도록 문서화했기 때문에 더 명확합니다.


@ComponentScan동일한 사용 사례에 대해 다음과 같이 사용 하고 있습니다. 이것은 BenSchro10의 XML 답변 과 동일 하지만 주석을 사용합니다. 둘 다 필터를 사용합니다.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);
    }
}

를 들어 스프링 (4) 나는 다음을 사용
(질문 4 세이며, 더 많은 사람들이 봄 3.1보다 봄 4 사용할 때 내가 그것을 게시하고있다)

@Configuration
@ComponentScan(basePackages = "com.example", 
  excludeFilters = @Filter(type=FilterType.REGEX,pattern="com\\.example\\.ignore\\..*")) 
public class RootConfig {
    // ...
}

이것은 Spring 3.0.5에서 작동합니다. 그래서 3.1에서 작동 할 것이라고 생각합니다.

<context:component-scan base-package="com.example">  
    <context:exclude-filter type="aspectj" expression="com.example.dontscanme.*" />  
</context:component-scan> 

XML을 통해이 작업을 수행 한 것 같지만 새로운 Spring 모범 사례에서 작업하는 경우 구성은 Java로되어 있으므로 다음과 같이 제외 할 수 있습니다.

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "net.example.tool",
  excludeFilters = {@ComponentScan.Filter(
    type = FilterType.ASSIGNABLE_TYPE,
    value = {JPAConfiguration.class, SecurityConfig.class})
  })

I think you should refactor your packages in more convenient hierarchy, so they are out of the base package.

But if you can't do this, try:

<context:component-scan base-package="com.example">
    ...
    <context:exclude-filter type="regex" expression="com\.example\.ignore.*"/>
</context:component-scan>

Here you could find more examples: Using filters to customize scanning


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.


You can also use @SpringBootApplication, which according to Spring documentation does the same functionality as the following three annotations: @Configuration, @EnableAutoConfiguration @ComponentScan in one annotation.

@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}

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 {}

참고URL : https://stackoverflow.com/questions/10725192/exclude-subpackages-from-spring-autowiring

반응형