programing

스프링 자동 배선에서 하위 패키지를 제외하시겠습니까?

oldcodes 2023. 2. 23. 23:05
반응형

스프링 자동 배선에서 하위 패키지를 제외하시겠습니까?

Spring 3.1에서 패키지/서브패키지를 자동배선 대상에서 제외하는 간단한 방법이 있습니까?

예를 들어 기본 패키지에 컴포넌트 스캔을 포함하려면com.example다른 사람들을 제외시킬 수 있는 간단한 방법이 있을까요?com.example.ignore?

(왜? 통합 테스트에서 일부 컴포넌트를 제외하려고 합니다.)

<exclude-filter>를 사용하여 패키지를 명시적으로 제외할 수 있을지는 잘 모르겠지만 regex 필터를 사용하면 다음과 같은 효과를 얻을 수 있을 것입니다.

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

주석을 기반으로 하려면 like@com.example.an과의 통합 테스트에서 제외할 각 클래스에 주석을 달아야 합니다.제외원IT 테스트. 그러면 컴포넌트 스캔은 다음과 같습니다.

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

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

사용하고 있다@ComponentScan동일한 사용 사례에 대해 다음과 같습니다.이것은 Ben Schro10의 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);
    }
}

Spring 4에서는 다음 항목을 사용합니다.
(질문이 4세이고 Spring 3.1보다 Spring 4를 더 많이 사용하고 있어 게시합니다.)

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

XML을 통해 이 작업을 수행한 것 같습니다만, Spring의 새로운 베스트 프랙티스로 작업하고 있는 경우는, 설정이 Java 로 되어 있기 때문에, 다음과 같이 제외할 수 있습니다.

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

이것은 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> 

패키지가 기본 패키지에서 벗어나도록 보다 편리한 계층으로 리팩터링해야 한다고 생각합니다.

그러나 이 작업을 수행할 수 없는 경우 다음을 시도해 보십시오.

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

여기서 더 많은 예를 찾을 수 있습니다.필터를 사용하여 검색 사용자 정의

한 가지 효과가 있을 것 같은 것은 다음과 같습니다.

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

또는 XML:

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

그러면 기본값이 덮어씁니다.resourcePattern어느 것이"**/*.class".

resourcePattern은 항상 같고 기본 패키지에 상대적이기 때문에 기본 패키지만 포함하는 것이 가장 안전한 방법인 것 같습니다.

기존 답변에 대한 추가 정보입니다.
하위 패키지에서 클래스를 제외하지만 기본 패키지에서 제외하지 않으려면 변경할 수 있습니다."com.example.ignore.*로."com.example.ignore.*..*"다음과 같이

스프링 기동시에 이것을 확인: 2.4.1.

이 답변에서 코드 조각을 가져왔습니다.

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

@ Boot Application을 사용할 수도 있습니다.Spring 설명서에 따르면 @Configuration, @Enable의 3가지 주석과 동일한 기능을 수행합니다.하나의 주석으로 자동 구성 @ComponentScan.

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

다음과 같이 특정 패키지를 포함하거나 제외할 수도 있습니다.

포함 및 제외(둘 다)

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

그냥 제외하다

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

언급URL : https://stackoverflow.com/questions/10725192/exclude-subpackages-from-spring-autowiring

반응형