Spring Boot: 명시적으로 생성한 빈만 얻는 방법

Spring Boot: 명시적으로 생성한 빈만 얻는 방법

2022-10-06 last update

7 minutes reading spring springboot todayilearned java
문제: 내 앱에서 명시적으로 생성한 모든 빈을 가져와야 합니다. applicationContext.getBeanDefinitionNames()를 호출할 때 빈 이름 목록을 얻었지만 그 중 많은 이름이 내가 명시적으로 생성한 것이 아니라 Spring에서 생성한 것이므로 관심이 없습니다. Spring에서 주입한 모든 빈이 "org.springframework"로 시작하는 것은 아니기 때문에 이 시점에서 필터링에 사용할 수 있는 명명 규칙은 없습니다.



솔루션: applicationContext.getBeanDefinitionNames()를 사용하고 루트 패키지 이름으로 빈을 필터링합니다.

package com.omiu.demo;

....

@Service
class PersonService {}

@Component
class PersonAnalyzer {}

class SimpleAnalyzer {}

@Configuration
class GeneralConfig {

    @Bean
    public SimpleAnalyzer simpleAnalyzer() {
        return new SimpleAnalyzer();
    }
}

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);

        List<Object> myBeans = Arrays.stream(applicationContext.getBeanDefinitionNames())
                .filter(beanName -> applicationContext.getBean(beanName).getClass().getPackage().getName().startsWith("com.omiu.demo"))
                .map(applicationContext::getBean)
                .collect(Collectors.toList());
    }
}


이것은 나에게 정확히 내가 관심 있는 5개의 Bean 목록을 제공합니다.