Skip to content

[Spring] 외부 모듈 @Import 하기 #1

Description

@dkdud9261

자동 설정 로직을 수행하는 빈 모듈을 만들고 외부에서 사용해보기


[ module ] 프로젝트에 특정 초기화 모듈을 만들고, 그것을 [ test ] 프로젝트에서 사용하고 싶다!

나는 한 프로젝트 내에서 두 패키지로 만들어서 테스트 해보았다. 실제로 다른 프로젝트에서 사용하고자 한다면 module 프로젝트를 maven repository에 업로드하고 test 프로젝트에 dependency 추가해서 사용하면 되겠다.

  1. module 프로젝트에 특정 초기화 로직을 수행하는 빈 만들기

    package com.example.module
    
    @Configuration
    class MyInitializerConfiguration {
        
        @Bean
        @ConditionalMissingBean
        fun myInitializer() = MyInitializer()
    }
    
    class MyInitializer: InitializingBean {
        
        override fun afterPropertiesSet() {
            // 모듈이 수행할 로직(프로퍼티 초기화 등)
        }
    }
    

    빈이 생성되고 난 후 자동으로 초기화 로직이 수행되도록 InitializingBean을 구현했다.

    빈이 InitializingBean을 구현하면 스프링 컨테이너는 빈이 생성되고 모든 프로퍼티가 설정된 후에 afterPropertiesSet()을 호출한다.

    이 방법 외에도 @PostConstruct, CommandLineRunner, ApplicationRunner를 사용할 수 있다.

    또한, 여러 모듈을 조합해서 사용하는 경우 특정 빈이 중복 생성되는 것을 방지하기 위해 @ConditionalOnMissingBean을 사용했다.

    @ConditionalOnMissingBean : 해당 빈이 빈 팩토리에 등록되지 않은 경우에만 빈을 등록한다.


  1. test 프로젝트에서 모듈 사용하기

    package com.example.test
    
    import com.example.module.MyInitializerConfiguration
    
    @Configuration
    @Import(MyInitializerConfiguration::class)
    class AppConfig
    

    @Import 어노테이션

    • 다른 설정 클래스를 현재의 설정 클래스로 가져오는 데 사용된다.
    • 주로 @Configuration 클래스를 가져올 때 사용하고, @Component 클래스도 가져올 수 있다.
    • 여러 설정 클래스를 하나의 설정 클래스로 가져올 수 있다.

어노테이션으로 모듈 사용하기


모듈 구성이 시시때때로 바뀌고, 모듈을 사용하는 클라이언트(여기서는 test 프로젝트) 입장에서 설정 클래스 이름을 장담할 수가 없겠다!
어노테이션으로 추상화해보자!

  1. @EnableInit 어노테이션 만들기

    package com.example.module
    
    @Import(MyInitializeConfiguration::class)
    @AutoConfigurationPackage
    annotation class EnableInit
    

    이렇게 하면 모듈의 구성이 바뀌었을 때, 클라이언트까지 수정사항이 전파될 필요 없이 어노테이션에 import 하는 구성 클래스만 바꿔주면 된다.

    @AutoConfigurationPackage : 자동 구성을 위한 패키지 스캔을 활성화 한다. 컴포넌트 스캔 패키지를 지정하지 않아도 해당 패키지 내 컴포넌트들을 자동으로 검색하게 한다.


  1. @EnableInit 어노테이션으로 모듈 사용하기

    package com.example.test
    
    import com.example.module.MyInitializerConfiguration
    
    @Configuration
    @EnableInit
    class AppConfig
    

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions