1. 개요

Spring 5는 애플리케이션 컨텍스트에서 Functional Bean 등록을 지원합니다.

간단히 말해서 GenericApplicationContext 클래스에 정의 된 registerBean () 메서드 의 오버로드 된 버전을 통해이 작업을 수행 할 수 있습니다 .

이 기능이 작동하는 몇 가지 예를 살펴 보겠습니다.

2. Maven 의존성

Spring 5 프로젝트 를 설정하는 가장 빠른 방법 spring-boot-starter-parent 의존성을 pom.xml 에 추가하여 Spring Boot 를 사용 하는 것입니다 .

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.0</version>
</parent>

우리는 또한 필요 스프링 부팅 스타터 웹스프링 부팅 선발 테스트 A의 웹 애플리케이션 컨텍스트를 사용하여, 우리의 예를 의 JUnit 테스트 :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

물론 빈을 등록하는 새로운 기능적 방법을 사용하기 위해 Spring Boot 는 필요하지 않습니다. 스프링 코어 의존성을 직접 추가 할 수도 있습니다.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.3.3</version>
</dependency>

3. 기능성 빈 등록

registerBean () API는 매개 변수로 기능 인터페이스의 두 가지 유형을받을 수 있습니다 :

  • 공급 업체 인수는 객체를 생성하는 데 사용
  • BeanDefinitionCustomizer의 가변 인자 커스터마이즈 하나 이상의 람다 식을 제공하는데 사용될 수있다 하는 BeanDefinition을 ; 이 인터페이스에는 하나의 customize () 메서드가 있습니다.

먼저 빈을 생성하는 데 사용할 매우 간단한 클래스 정의를 생성 해 보겠습니다.

public class MyService {
    public int getRandomNumber() {
        return new Random().nextInt(10);
    }
}

JUnit 테스트 를 실행하는 데 사용할 수 있는 @SpringBootApplication 클래스 도 추가해 보겠습니다 .

@SpringBootApplication
public class Spring5Application {
    public static void main(String[] args) {
        SpringApplication.run(Spring5Application.class, args);
    }
}

다음으로 @SpringBootTest 어노테이션을 사용하여 테스트 클래스를 설정 하여 GenericWebApplicationContext 인스턴스 를 만들 수 있습니다 .

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring5Application.class)
public class BeanRegistrationIntegrationTest {
    @Autowired
    private GenericWebApplicationContext context;
   
    //...
}

예제에서는 GenericWebApplicationContext 유형을 사용하고 있지만 모든 유형의 애플리케이션 컨텍스트를 동일한 방식으로 빈을 등록하는 데 사용할 수 있습니다.

인스턴스 생성을 위해 람다 표현식을 사용하여 빈을 등록하는 방법 살펴 보겠습니다 .

context.registerBean(MyService.class, () -> new MyService());

이제 빈을 검색하고 사용할 수 있는지 확인하겠습니다.

MyService myService = (MyService) context.getBean("com.baeldung.functional.MyService"); 
 
assertTrue(myService.getRandomNumber() < 10);

이 예제에서 빈 이름이 명시 적으로 정의되지 않은 경우 클래스의 소문자 이름에서 결정된다는 것을 알 수 있습니다. 위의 동일한 방법을 명시적인 빈 이름과 함께 사용할 수도 있습니다.

context.registerBean("mySecondService", MyService.class, () -> new MyService());

다음 으로 람다 표현식을 추가하여 Bean을 등록하는 방법 살펴 보겠습니다 .

context.registerBean("myCallbackService", MyService.class, 
  () -> new MyService(), bd -> bd.setAutowireCandidate(false));

이 인수는 autowire-candidate 플래그 또는 기본 플래그 와 같은 빈 속성을 설정하는 데 사용할 수있는 콜백입니다 .

4. 결론

이 빠른 예제에서 우리는 빈을 등록하는 기능적인 방법을 어떻게 사용할 수 있는지 보았습니다.

예제의 소스 코드는 GitHub 에서 찾을 수 있습니다 .