programing

스프링: 특정 인터페이스 및 유형의 모든 Bean을 가져옵니다.

madecode 2023. 3. 4. 15:22
반응형

스프링: 특정 인터페이스 및 유형의 모든 Bean을 가져옵니다.

Spring Boot 어플리케이션에서 Java에 인터페이스가 있다고 가정합니다.

public interface MyFilter<E extends SomeDataInterface> 

(를 들어 Spring의 퍼블릭인터페이스 ApplicationListener <E extends ApplicationEvent >가 있습니다).

다음과 같은 몇 가지 구현이 있습니다.

@Component
public class DesignatedFilter1 implements MyFilter<SpecificDataInterface>{...}

@Component
public class DesignatedFilter2 implements MyFilter<SpecificDataInterface>{...}

@Component
public class DesignatedFilter3 implements MyFilter<AnotherSpecificDataInterface>{...}

또한 일부 개체에서는 MyFilter < SpecificData 를 구현하는 모든 필터를 사용하고 싶습니다.인터페이스 > 단 MyFilter <AnotherSpecific Data는 아니다인터페이스 >

이것의 구문은 무엇입니까?

다음은 SpecificData를 확장하는 유형을 가진 모든 MyFilter 인스턴스를 주입합니다.범용 인수로 목록에 인터페이스합니다.

@Autowired
private List<MyFilter<? extends SpecificDataInterface>> list;

간단하게 사용할 수 있습니다.

@Autowired
private List<MyFilter<SpecificDataInterface>> filters;

2020년 7월 28일 편집:

필드 주입이 더 이상 권장되지 않으므로 필드 주입 대신 생성자 주입을 사용해야 합니다.

생성자 주입 사용:

class MyComponent {

  private final List<MyFilter<SpecificDataInterface>> filters;

  public MyComponent(List<MyFilter<SpecificDataInterface>> filters) {
    this.filters = filters;
  }
  ...
}

당신이 원하는 경우Map<String, MyFilter>, 여기서key(String)는 빈 이름을 나타냅니다.

private final Map<String, MyFilter> services;

public Foo(Map<String, MyFilter> services) {
  this.services = services;
}

어떤 것이recommended대체 수단:

@Autowired
private Map<String, MyFilter> services;

지도가 필요한 경우 아래 코드가 적용됩니다.열쇠는 정의된 방식입니다.

private Map<String, MyFilter> factory = new HashMap<>();

@Autowired
public ReportFactory(ListableBeanFactory beanFactory) {
  Collection<MyFilter> interfaces = beanFactory.getBeansOfType(MyFilter.class).values();
  interfaces.forEach(filter -> factory.put(filter.getId(), filter));
}

언급URL : https://stackoverflow.com/questions/40286047/spring-get-all-beans-of-certain-interface-and-type

반응형