> Java > java지도 시간 > 본문

@Named를 통한 도전과제 공개

WBOY
풀어 주다: 2024-08-30 06:03:35
원래의
1090명이 탐색했습니다.

끊임없이 진화하는 컨텍스트 및 종속성 주입(CDI) 환경에서 개발자는 Bean 이름 지정, 기본 구현 및 잠재적 충돌과 관련된 장애물에 자주 직면합니다. 이 문서에서는 CDI의 @Named 주석과 관련된 잠재적 위험에 대해 자세히 살펴봅니다. 우리는 그 복잡성을 조사하고, 문제가 있는 시나리오를 밝히고, SmallRye의 @Identifier 사용을 포함한 대체 접근 방식에 대해 논의할 것입니다. 또한, 견고하고 유지 관리가 용이한 Jakarta EE
구축을 위한 모범 사례에 대한 통찰력을 제공할 것입니다. 응용 프로그램입니다.

@기본 이해

@Default 주석은 특정 구현을 특정 인터페이스나 Bean 유형의 기본 구현으로 명시적으로 표시하기 위한 CDI의 유용한 도구입니다. 이는 동일한 인터페이스의 여러 구현을 처리할 때 작동하므로 개발자는 다른 한정자를 사용하지 않을 때 기본적으로 어떤 구현을 삽입해야 하는지 지정할 수 있습니다.

GreetingService 인터페이스의 여러 구현이 존재하는 시나리오를 고려해보세요.

@Default
public class DefaultGreetingService implements GreetingService {

  @Override
  public String greet(String name) {
    return "Hello, " + name;
  }
}
로그인 후 복사
public class SpecialGreetingService implements GreetingService {

  @Override
  public String greet(String name) {
    return "Greetings, " + name + "!";
  }
}
로그인 후 복사

한정자를 지정하지 않고 Bean을 주입하는 경우 CDI는 @Default로 표시된 Bean을 기본값으로 사용합니다. 이는 여러 구현이 포함된 시나리오에서 명확한 기본 선택을 제공하는 데 유용합니다.

@Inject
private GreetingService greetingService; // Injects the @Default implementation
로그인 후 복사

@Default 사용은 선택 사항이지만 특히 여러 구현이 있는 인터페이스를 처리할 때 사용하는 것이 좋습니다. 명확하고 일관된 기본 옵션을 제공하여 빈 주입 중 모호함과 예상치 못한 동작을 방지합니다.

@Named 탐색 - 양날의 검

@Named 한정자는 CDI에서 사람이 읽을 수 있는 이름이나 식별자를 빈에 할당하는 기본적인 역할을 합니다. 개발자들은 빈을 다른 컴포넌트에 주입할 때 빈을 이름으로 참조하기 위해 종종 이를 사용합니다.

그러나 @Named에는 특히 추가 한정자 없이 사용할 때 고유한 문제가 있습니다. 기본적으로 CDI는 규정되지 않은 클래스 이름을 Bean 이름과 연관시킵니다. 이로 인해 @Default 한정자와 충돌이 발생하여 Bean 주입 중에 예상치 못한 동작이 발생할 수 있습니다.

@Named
public class MyBean {
  // Implementation
}

로그인 후 복사

명시적인 한정자 없이 MyBean을 주입하는 경우 CDI는 @Default 한정자가 아닌 @Named 한정자만 추가합니다. @Default 한정자는 Bean 또는 해당 한정자에 명시적으로 지정된 경우에만 적용됩니다.

@Inject
private MyBean myBean;
로그인 후 복사

이 경우, 같은 타입명의 다른 Bean이 있으면 모호성이 발생할 수 있습니다. 예를 들어 MyBean이라는 또 다른 Bean이 있는 경우 주입이 모호해집니다.

이 문제를 해결하려면 개발자는 삽입하려는 Bean을 명시적으로 한정해야 합니다.

@Inject
@Named("myBean")
private MyBean myBean;
로그인 후 복사

또는 개발자는 각 Bean에 대해 사용자 정의 한정자를 활용하여 모호성을 제거할 수 있습니다.

문제가 있는 경우: 모호함 및 의도하지 않은 기본값

추가 한정자 없이 @Named를 사용하고 동일한 유형의 구현이 여러 개 존재하는 경우 모호성이 발생합니다. 다음 시나리오를 고려하십시오.

@Named
public class ServiceA implements Service {
  // Implementation
}
로그인 후 복사
@Named
public class ServiceB implements Service {
  // Implementation
}
로그인 후 복사

명시적인 한정자 없이 서비스를 주입하면 두 Bean이 유형별로 일치하고 이름이나 한정자가 구별되지 않으므로 모호성이 발생할 수 있습니다.

@Inject
private Service service;
로그인 후 복사

이 경우 CDI는 @Default를 암시적으로 추가하거나 모호성을 해결하려고 시도하지 않아 모호한 종속성으로 인해 주입이 실패하게 됩니다.

대안: SmallRye Common의 @Identifier 소개

@Named가 제기한 문제를 인식하면서 개발자는 종종 Bean 식별을 보다 명시적으로 제어하기 위한 대안을 모색합니다. 그러한 대안 중 하나는
의 @Identifier 주석입니다. 스몰라이 커먼. 이 주석은 Bean 이름 지정에 대한 보다 명확하고 제어된 접근 방식을 제공하여 충돌 및 예상치 못한 기본값의 위험을 줄입니다. 각 애플리케이션에 고유한 값이 필요한 @Named와 달리 @Identifier는 유형이 다른 한 동일한 식별자 값을 가진 여러 Bean을 허용합니다. 이러한 유연성은 동일한 인터페이스 또는 관련 유형의 다양한 구현을 처리할 때 특히 유용합니다.

@Identifier를 사용하려면 빈 클래스에 주석을 추가하고 식별자 값을 지정하세요.

@Identifier("payment")
public class DefaultPaymentProcessor implements PaymentProcessor {
  // Implementation
}
로그인 후 복사
@Identifier("payment")
public class LegacyPaymentGateway implements PaymentGateway {
  // Implementation
}
로그인 후 복사

@Identifier를 사용하여 빈을 주입하는 것은 간단합니다.

public class Client {
  @Inject
  @Identifier("payment")
  PaymentProcessor processor;

  @Inject
  @Identifier("payment")
  PaymentGateway gateway;

}
로그인 후 복사

여기에서는 PaymentProcessor와 PaymentGateway 유형이 다르기 때문에 "결제" @Identifier 값이 여러 Bean에 재사용됩니다. 이러한 유연성은 @Named에서는 허용되지 않습니다.
값은 애플리케이션 전체에서 고유해야 합니다.

Another alternative to @Named is to create custom qualifiers. Custom qualifiers are user-defined annotations that can be used to identify and qualify beans. They offer the most granular control over bean selection and can be tailored to specific needs of the application.

To create a custom qualifier, follow these steps:

  1. Define a new annotation class.
  2. Annotate the annotation class with @Qualifier.
  3. Optionally, provide a default value for the qualifier.

For example, the following custom qualifier named DefaultPaymentGateway indicates the default payment gateway implementation:

@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface DefaultPaymentGateway {

}
로그인 후 복사

To use the custom qualifier, annotate the bean class with it:

@DefaultPaymentGateway
public class StandardPaymentGateway implements PaymentGateway {
  // Implementation
}
로그인 후 복사
public class ExpressPaymentGateway implements PaymentGateway {
  // Implementation
}
로그인 후 복사

Then, inject the bean using the qualifier:

@Inject
@DefaultPaymentGateway
private PaymentGateway paymentGateway;
로그인 후 복사

Choosing the Right Approach

The best approach for bean identification depends on the specific needs of the application. For simple applications, @Named may be sufficient. For more complex applications, @Identifier or
custom qualifiers offer more control and flexibility.

The following table summarizes the pros and cons of each approach:

Approach Pros Cons
@Named Simple, widely supported Can be ambiguous, conflicts with @Default
@Identifier Clearer identification, no conflicts with @Default Requires additional annotations
Custom qualifiers Maximum flexibility, fine-grained control Requires upfront effort to define and maintain

For further confirmation, you can refer to the official CDI specification

Unveiling Challenges with @Named

Conclusion: Strategic Choices for Bean Naming and Defaults

In conclusion, the potential pitfalls associated with @Named underscore the need for careful consideration when using this annotation in CDI. Ambiguity and unintended defaults can arise when relying on implicit naming, especially in the presence of multiple implementations. Developers are encouraged to explore alternatives such as @Identifier from SmallRye Common for a more controlled and explicit approach to bean identification. Embracing explicit qualification, custom qualifiers, and alternative approaches ensures a smoother and more controlled CDI experience, leading to robust and maintainable Java.

위 내용은 @Named를 통한 도전과제 공개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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