programing

스프링 @자동 배선 및 @자격자

stoneblock 2023. 7. 28. 21:46

스프링 @자동 배선 및 @자격자

다음으로 자동 감지됩니까?@Autowired?
다음과 같은 경우 이름에 의한 종속성 주입입니까?@Qualifier사용하시겠습니까?
이러한 주석을 사용하여 어떻게 세터 및 생성자 주입을 할 수 있습니까?

사용할 수 있습니다.@Qualifier와 함께@Autowired실제로 봄에는 모호한 콩 유형이 발견되면 콩을 명시적으로 선택하도록 요청할 것이며, 이 경우 한정자를 제공해야 합니다.

예를 들어 다음과 같은 경우에는 한정자를 제공해야 합니다.

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

편집:

Lombok 1.18.4에서는 @Qualifier가 있을생성자 주입보일러 플레이트를 피할있으므로 이제 다음 작업을 수행할 수 있습니다.

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
@RequiredArgsConstructor
public Payroll {
   @Qualifier("employee") private final Person person;
}

새 lombok.config 규칙 복사 가능Annotations를 사용하는 경우(프로젝트 루트의 lombok.config에 다음을 배치함):

# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

이것은 최근 lombok 1.18.4에 소개되었습니다.

메모

필드 또는 세터 주입을 사용하는 경우 아래와 같은 필드 또는 세터 기능 위에 @Autowired 및 @Qualifier를 배치해야 합니다(둘 중 하나라도 작동합니다).

public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

또는

public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

생성자 주입을 사용하는 경우 주석이 생성자에 배치되어야 하며 그렇지 않으면 코드가 작동하지 않습니다.아래와 같이 사용합니다 -

public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

@Qualifier주석은 같은 유형의 빈이 여러 개 있는 경우 자동 배선 충돌을 해결하는 데 사용됩니다.

@Qualifier주석은 주석이 달린 모든 클래스에서 사용할 수 있습니다.@Component또는 주석이 달린 방법에 대해@Bean이 주석은 생성자 인수 또는 메서드 매개 변수에도 적용할 수 있습니다.

예:-

public interface Vehicle {
     public void start();
     public void stop();
}

두 가지 콩이 있습니다. 차량 및 자전거가 차량 인터페이스를 구현합니다.

@Component(value="car")
public class Car implements Vehicle {

     @Override
     public void start() {
           System.out.println("Car started");
     }

     @Override
     public void stop() {
           System.out.println("Car stopped");
     }
 }

@Component(value="bike")
public class Bike implements Vehicle {

     @Override
     public void start() {
          System.out.println("Bike started");
     }

     @Override
     public void stop() {
          System.out.println("Bike stopped");
     }
}

차량 서비스 시 다음을 사용하여 바이크 빈 주입@Autowired와 함께@Qualifier주석사용하지 않은 경우@Qualifier그것은 독특한 빈 정의를 던지지 않을 것입니다.예외.

@Component
public class VehicleService {

    @Autowired
    @Qualifier("bike")
    private Vehicle vehicle;

    public void service() {
         vehicle.start();
         vehicle.stop();
    }
}

참조:- @ 한정자 주석 예제

@Autowired유형별로 자동 배선(또는 검색)
@Qualifier 배선 검색)하기
른대옵의 다른 대안 @Qualifier이라@Primary

@Component
@Qualifier("beanname")
public class A{}

public class B{

//Constructor
@Autowired  
public B(@Qualifier("beanname")A a){...} //  you need to add @autowire also 

//property
@Autowired
@Qualifier("beanname")
private A a;

}

//If you don't want to add the two annotations, we can use @Resource
public class B{

//property
@Resource(name="beanname")
private A a;

//Importing properties is very similar
@Value("${property.name}")  //@Value know how to interpret ${}
private String name;
}

@value에 대한 자세한 정보

언급URL : https://stackoverflow.com/questions/40830548/spring-autowired-and-qualifier