복붙노트

[SPRING] 런타임시 봄에 추가 빈 설정 파일을로드하는 법

SPRING

런타임시 봄에 추가 빈 설정 파일을로드하는 법

나는 스프링 애플리케이션을 가지고 있으며, 앞으로 더 많은 클래스를 개발할 것이며,이 클래스를 위해 추가 구성 파일을 사용하여 기존의 파일을 덮어 쓰지 않고 빈을 정의 할 것이다. 그런 다음 동적으로로드하는 방법은 무엇입니까? ApplicationContextAware의 인터페이스가 있다는 것을 알고 있습니다. 새로운 구성 파일의 사용 가능 여부를 확인하는 Bean을 실행할 수 있습니다.

setApplicationContext(ApplicationContext applicationContext)

그렇다면 ApplicationContext를 사용하여 추가 구성 파일을로드하는 방법은 무엇입니까?

최신 정보: 응용 프로그램이 XML에서로드 된 경우 ApplicationContext를 ClassPathXmlApplicationContext로 변환 한 다음 load 메서드를 사용할 수 있지만 AnnotationConfigApplicationContext 인 경우 패키지를 검색하는 검사 방법 만있는 것이지만 xml에서로드하려면 어떻게해야합니까?

최신 정보: 다음은 사용하고자하는 코드입니다. 스프링 통합을 사용하여 폴드를 모니터링합니다. 런타임에 jar 파일을 클래스 경로에 넣은 다음 xml 구성을 해당 폴더에 저장하면 loadAdditionBeans 함수가 실행됩니다. , xml File 객체가 전달 될 때 수행해야하는 작업은 해당 파일의 컨텍스트를 현재 컨텍스트에 추가하고 자식 컨텍스트를 만들지 않는 것입니다.

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.ServiceActivator;

import java.io.File;

@MessageEndpoint
public class FolderWatcher implements ApplicationContextAware {
    //private ApplicationContext ctx;
    private AnnotationConfigApplicationContext ctx;  // it's a spring boot,so the ctx is AnnotationConfigApplicationContext
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx=(AnnotationConfigApplicationContext)applicationContext;
    }
    @ServiceActivator
    public void loadAdditionBeans(File file){
        /*
        file is an xml configuration file, how to load the beans defined it into the currect context,
        I don't what to have another hierarchy, since that will make the beans defined in the file not
        available in parent.
         */
    }

}

해결법

  1. ==============================

    1.

    PathMatchingResourcePatternResolver pmrl = new PathMatchingResourcePatternResolver(context.getClassLoader());
      Resource[] resources = pmrl.getResources(
        "classpath*:com/mycompany/**/applicationContext.xml"
      );
    
    for (Resource r : resources) {
       GenericApplicationContext createdContext = new GenericApplicationContext(context);
       XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(createdContext);
       int i = reader.loadBeanDefinitions(r);
    }
    

    위의 코드를 살펴보고 문제를 해결하는 데 도움이되는지 알려주십시오.

  2. ==============================

    2.클래스 패스 스캐닝을 사용하고 있지만 XML에서 추가 구성을로드하려는 경우 @Configuration 클래스에서 @ImportResource 주석을 사용하고 필요한 XML 리소스를 가져올 수 있습니다. @Configuration @ImportResource ({ "classpath * : / rest_config.xml"}) 공용 클래스 MyConfig {  ... } 그렇게하면 레거시 XML 구성을 새로운 Java 구성과 쉽게 섞을 수 있으며 예를 들어 전체 구성을 한 번에 마이그레이션 할 필요가 없습니다.

    클래스 패스 스캐닝을 사용하고 있지만 XML에서 추가 구성을로드하려는 경우 @Configuration 클래스에서 @ImportResource 주석을 사용하고 필요한 XML 리소스를 가져올 수 있습니다. @Configuration @ImportResource ({ "classpath * : / rest_config.xml"}) 공용 클래스 MyConfig {  ... } 그렇게하면 레거시 XML 구성을 새로운 Java 구성과 쉽게 섞을 수 있으며 예를 들어 전체 구성을 한 번에 마이그레이션 할 필요가 없습니다.

    희망이 도움이됩니다.

  3. from https://stackoverflow.com/questions/27580811/how-to-load-additional-bean-configuration-file-in-spring-at-run-time by cc-by-sa and MIT license