> Java > java지도 시간 > 본문

Quarkus에서 합성 콩을 탐색합니다. 강력한 확장 메커니즘

PHPz
풀어 주다: 2024-08-30 06:02:32
원래의
279명이 탐색했습니다.

Exploring Synthetic Beans in Quarkus. A Powerful Extension Mechanism

Quarkus의 세계에서 종속성 주입 영역은 풍부하고 다양하며 개발자에게 Bean을 관리하고 제어할 수 있는 다양한 도구를 제공합니다. 그러한 도구 중 하나가 합성 콩이라는 개념입니다. 합성 빈은 속성이 Java 클래스, 메소드 또는 필드에서 파생되지 않은 빈을 등록할 수 있게 해주는 강력한 확장 메커니즘입니다. 대신 합성 빈의 모든 속성은 확장으로 정의됩니다.

이 기사에서는 Quarkus의 합성 콩 세계에 대해 자세히 살펴보겠습니다. 합성 콩의 필요성, 실제 적용 방법, Quarkus 애플리케이션에서 합성 콩을 생성하고 사용하는 방법을 살펴보겠습니다.

합성콩의 이해

Quarkus에서 빈은 CDI(컨텍스트 및 종속성 주입) 프레임워크에 의해 관리되는 애플리케이션의 구성 요소입니다. 일반적으로 CDI Bean은 @ApplicationScoped, @RequestScoped 또는 @Inject와 같은 다양한 CDI 주석으로 주석이 달린 Java 클래스입니다. 이 주석
CDI가 빈의 수명주기와 주입을 자동으로 관리할 수 있습니다.

그러나 기존 CDI 모델에 딱 들어맞지 않는 Bean을 등록해야 하는 상황이 있을 수 있습니다. 이것은 합성 콩이 작용하는 곳입니다. 합성 빈은 확장에 의해 생성되며 해당 확장에 의해 완전히 정의된 속성을 갖습니다. 일반 CDI 세계에서는 AfterBeanDiscovery.addBean() 및 SyntheticComponents.addBean() 메서드를 사용하여 이를 달성합니다. Quarkus에서는 SyntheticBeanBuildItem을 사용하여 이 작업을 수행합니다.

언제 합성 콩이 필요합니까?

그럼 언제 Quarkus에서 합성빈을 사용해야 할까요? 합성 콩은 다음과 같은 경우에 강력한 도구입니다.

  1. 타사 라이브러리 통합: CDI 주석이 없지만 CDI 기반 애플리케이션에 통합해야 하는 타사 라이브러리로 작업하고 있습니다. 합성콩을 사용하면 이러한 격차를 해소할 수 있습니다.

  2. 동적 Bean 등록: 구성이나 기타 요인에 따라 런타임에 Bean을 동적으로 등록해야 합니다. 합성콩을 사용하면 즉시 콩을 생성하고 등록할 수 있는 유연성을 얻을 수 있습니다.

  3. 맞춤형 Bean 관리: 표준 CDI 주석으로는 달성할 수 없는 Bean의 범위와 동작에 대한 세밀한 제어가 필요합니다.

  4. 특수 Bean 구현: 기존 Java 클래스나 메소드에 해당하지 않는 고유한 속성을 가진 특수 Bean을 생성하려고 합니다.

  5. 테스트를 위한 모의 종속성: 합성 빈은 테스트 목적으로 종속성을 모의하고 모의 구현을 삽입하는 유용한 방법을 제공합니다.

합성완료빌드아이템

SynesisFinishedBuildItem은 CDI Bean 검색 및 등록 프로세스가 완료되었음을 나타내는 데 사용됩니다. 이를 통해 확장 프로그램은 등록된 Bean과 상호 작용하는 것이 안전한 시기를 알 수 있습니다.

예:

@BuildStep  
void onSynthesisFinished(SynthesisFinishedBuildItem synthesisFinished){
    // CDI bean registration is complete, can now safely interact with beans
    }
로그인 후 복사

SyntheticBeansRuntimeInitBuildItem

SyntheticBeansRuntimeInitBuildItem은 모든 합성 Bean이 초기화된 후 런타임에 호출될 콜백을 등록하는 데 사용됩니다. 이는 합성 Bean과 관련된 추가 초기화 로직을 수행해야 하는 경우 유용합니다.

예:

@BuildStep
SyntheticBeansRuntimeInitBuildItem initSyntheticBeans(){

    return new SyntheticBeansRuntimeInitBuildItem(ids->{
    // Perform logic with initialized synthetic beans
    });

    }
로그인 후 복사

SyntheticBeansRuntimeInitBuildItem에 전달된 콜백은 Set 초기화된 모든 합성빈의 ID를 담고 있습니다.

요약하면 SynesisFinishedBuildItem은 Bean 검색이 완료되었음을 나타내는 반면 SyntheticBeansRuntimeInitBuildItem은 합성 Bean에 따라 로직 초기화를 허용합니다.

SyntheticBeanBuildItem을 사용하여 합성 콩 생성

Quarkus에서는 SyntheticBeanBuildItem 클래스 덕분에 합성 빈을 생성하는 과정이 간단해졌습니다. 합성 빈을 생성하고 사용하는 단계를 살펴보겠습니다.

  1. 합성 콩 클래스 생성: 합성 콩 클래스를 정의하는 것부터 시작합니다. 이 클래스는 합성 빈의 기초가 될 것입니다.
package com.iqnev;

public class MySyntheticBean {

  // Define the behavior and attributes of your synthetic bean
  public void printMessage() {
    System.out.println("Hello from synthetic bean!");
  }
}
로그인 후 복사
  1. Quarkus 확장 만들기: 합성 빈을 등록하려면 Quarkus 확장을 만들어야 합니다. 이 확장 클래스는 SyntheticBeanBuildItem을 사용하여 Bean을 구성합니다.

바이트코드 생성 접근 방식

package com.iqnev;

import io.quarkus.arc.deployment.SyntheticBeanBuildItem;

public class MySyntheticBeanExtension {

  @BuildStep
  SyntheticBeanBuildItem syntheticBean() {
    return SyntheticBeanBuildItem
        .configure(MySyntheticBean.class)
        .scope(ApplicationScoped.class)
        .creator(mc -> {
          mc.returnValue(new MySyntheticBean());
        })
        .done();
  }
}
로그인 후 복사

SyntheticBeanBuildItem의 .creator() 메소드는 런타임에 합성 Bean의 인스턴스를 생성하는 바이트코드를 생성하는 데 사용됩니다.

.creator()에 전달된 인수는 Consumer입니다. 메소드 내에서 Java 바이트코드를 생성할 수 있습니다.

이 예에서는:

  1. mc is the MethodCreator instance
  2. mc.returnValue(new MySyntheticBean()) generates the bytecode to create a new instance of MySyntheticBean and return it from the method.

So essentially, we are telling Quarkus to generate a method that looks something like:

MySyntheticBean createSyntheticBean(){
    return new MySyntheticBean();
    }
로그인 후 복사

This generated method will then be called to instantiate the MySyntheticBean when it needs to be injected or used.

The reason bytecode generation is used is that synthetic beans do not correspond to real Java classes/methods, so we have to explicitly generate a method to instantiate them

The output of SyntheticBeanBuildItem is bytecode recorded at build time. This limits how instances are created at runtime. Common options are:

  1. Generate bytecode directly via .creator()
  2. Use a BeanCreator subclass
  3. Produce instance via @Recorder method

Recorder Approach

The @Record and .runtimeValue() approaches are alternate ways of providing instances for synthetic beans in Quarkus.

This allows you to instantiate the synthetic bean via a recorder class method annotated with @Record(STATIC_INIT).

For example:

@Recorder
public class MyRecorder {

  @Record(STATIC_INIT)
  public MySyntheticBean createBean() {
    return new MySyntheticBean();
  }

}

  @BuildStep
  SyntheticBeanBuildItem syntheticBean(MyRecorder recorder) {
    return SyntheticBeanBuildItem
        .configure(MySyntheticBean.class)
        .runtimeValue(recorder.createBean());
  }
로그인 후 복사

Here the .runtimeValue() references the recorder method to instantiate the bean. This allows passing a RuntimeValue directly to provide the synthetic bean instance.

For example:

@BuildStep 
SyntheticBeanBuildItem syntheticBean(){

    RuntimeValue<MySyntheticBean> bean= //...

    return SyntheticBeanBuildItem
    .configure(MySyntheticBean.class)
    .runtimeValue(bean);

    }
로그인 후 복사

The RuntimeValue could come from a recorder, supplier, proxy etc.

So in summary:

  • @Record is one approach to generate the RuntimeValue
  • .runtimeValue() sets the RuntimeValue on the SyntheticBeanBuildItem

They both achieve the same goal of providing a runtime instance, just in slightly different ways.

When it comes to providing runtime instances for synthetic beans in Quarkus, I would consider using recorders (via @Record) to be a more advanced approach compared to directly generating bytecode
with .creator() or supplying simple RuntimeValues.

Here are some reasons why using recorders can be more advanced:

  • More encapsulation - The logic to instantiate beans is contained in a separate recorder class rather than directly in build steps. This keeps build steps lean.
  • Reuse - Recorder methods can be reused across multiple synthetic beans rather than rewriting creator logic.
  • Runtime data - Recorder methods execute at runtime so they can leverage runtime resources, configs, services etc. to construct beans.
  • Dependency injection - Recorder methods can inject other services.
  • Life cycle control - Recorder methods annotated with @Record(STATIC_INIT) or @Record(RUNTIME_INIT) give more control over bean instantiation life cycle.
  • Managed beans - Beans instantiated inside recorders can themselves be CDI managed beans.

So in summary, recorder methods provide more encapsulation, flexibility and access to runtime data and services for instantiating synthetic beans. They allow for more advanced bean production logic compared to direct bytecode generation.

However, direct bytecode generation with .creator() can still be useful for simple cases where recorders may be overkill. But as synthetic bean needs grow, recorders are a more powerful and
advanced approach.

It is possible to configure a synthetic bean in Quarkus to be initialized during the RUNTIME_INIT phase instead of the default STATIC_INIT phase.

Here is an example:

@BuildStep
@Record(RUNTIME_INIT)
SyntheticBeanBuildItem lazyBean(BeanRecorder recorder){

    return SyntheticBeanBuildItem
    .configure(MyLazyBean.class)
    .setRuntimeInit() // initialize during RUNTIME_INIT
    .runtimeValue(recorder.createLazyBean());

    }
로그인 후 복사

The key points are:

  • Use setRuntimeInit() on the SyntheticBeanBuildItem to mark it for RUNTIME_INIT
  • The recorder method must be annotated with @Record(RUNTIME_INIT)
  • The runtime init synthetic beans cannot be accessed during STATIC_INIT

So in summary, synthetic beans can be initialized lazily during RUNTIME_INIT for cases where eager STATIC_INIT instantiation is not needed. This allows optimizing startup time.

Use the Synthetic Bean: Now that your synthetic bean is registered, you can inject and use it in your application.

package com.iqnev;

import javax.inject.Inject;

public class MyBeanUser {

  @Inject
  MySyntheticBean mySyntheticBean;

  public void useSyntheticBean() {
    // Use the synthetic bean in your code
    mySyntheticBean.printMessage();
  }
}
로그인 후 복사

Running Your Application: Build and run your Quarkus application as usual, and the synthetic bean will be available for injection and use.

Conclusion

Synthetic beans in Quarkus provide a powerful mechanism for integrating external libraries, dynamically registering beans, and customizing bean behavior in your CDI-based applications. These beans, whose attributes are defined by extensions rather than Java classes, offer flexibility and versatility in managing dependencies.

이 기사에서 살펴본 것처럼 Quarkus에서 합성 콩을 만들고 사용하는 과정은 간단합니다. SyntheticBeanBuildItem 및 Quarkus 확장을 활용하면 기존 CDI와 보다 전문적이거나 동적인 Bean 등록 요구 사항 간의 격차를 원활하게 메울 수 있습니다.

계속 진화하는 Java 프레임워크 환경에서 Quarkus는 합성 빈과 같은 혁신적인 솔루션을 제공하여 계속해서 두각을 나타내고 있으며 현대적이고 효율적이며 유연한 애플리케이션 개발을 위한 강력한 선택입니다. Quarkus에서 합성 빈의 힘을 활용하고 의존성 주입을 한 단계 더 발전시키세요!

위 내용은 Quarkus에서 합성 콩을 탐색합니다. 강력한 확장 메커니즘의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!