programing

Spring에서 조건부 자동 연결을 수행하는 방법은 무엇입니까?

minecode 2021. 1. 15. 07:58
반응형

Spring에서 조건부 자동 연결을 수행하는 방법은 무엇입니까?


조건에 따라 다른 빈을 Spring 관리 빈에 자동 연결하려고 시도한 사람이 있습니까? 예를 들어 어떤 조건이 충족되면 클래스 A를 주입하고 그렇지 않으면 B? Google 검색 결과 중 하나에서 SpEL (Spring Expression Language)로 가능하다는 것을 보았지만 작동하는 예제를 찾을 수 없습니다.


이를 달성하는 방법에는 여러 가지가 있습니다. 대부분 이것은 수행하려는 컨디셔닝에 따라 다릅니다.

공장 콩

조건부 연결을 수행하기 위해 간단한 팩토리 빈을 구현할 수 있습니다. 이러한 팩토리 빈은 복잡한 컨디셔닝 로직을 포함 할 수 있습니다.

public MyBeanFactoryBean implements FactoryBean<MyBean> {

    // Using app context instead of bean references so that the unused 
    // dependency can be left uninitialized if it is lazily initialized
    @Autowired
    private ApplicationContext applicationContext;

    public MyBean getObject() {
        MyBean myBean = new MyBean();
        if (true /* some condition */) {
            myBean.setDependency(applicationContext.getBean(DependencyX.class));
        } else {
            myBean.setDependency(applicationContext.getBean(DependencyY.class));
        }
        return myBean;
    }

    // Implementation of isSingleton => false and getObjectType

}

아마도 조금 더 나은 접근 방식은 당신이 당신의 애플리케이션 컨텍스트에 그러한 빈을 하나만 갖고 싶은 경우에 팩토리 빈 을 사용하여 의존성 빈 을 만드는 것입니다 :

public MyDependencyFactoryBean implements FactoryBean<MyDependency> {

    public MyDependency getObject() {
        if (true /* some condition */) {
            return new MyDependencyX();
        } else {
            return new MyDependencyY();
        }
    }

    // Implementation of isSingleton => false and getObjectType

}

SpEL

SpEL에는 많은 가능성이 있습니다. 가장 일반적인 것은 시스템 속성 기반 조건입니다.

<bean class="com.example.MyBean">
    <property name="dependency" value="#{systemProperties['foo'] == 'bar' ? dependencyX : dependencyY}" />
</bean>

속성 자리 표시 자

속성 자리 표시자가 빈 참조를 확인하도록 할 수 있습니다. 종속성 이름은 애플리케이션 구성의 일부일 수 있습니다.

<bean class="com.example.MyBean">
    <property name="dependency" ref="${dependencyName}" />
</bean>

봄 프로필

일반적으로 평가하려는 조건은 전체 Bean 세트를 등록해야하거나 등록하지 않아야 함을 의미합니다. 이를 위해 스프링 프로파일을 사용할 수 있습니다.

<!-- Default dependency which is referred by myBean -->
<bean id="dependency" class="com.example.DependencyX" />

<beans profile="myProfile">
    <!-- Override `dependency` definition if myProfile is active -->
    <bean id="dependency" class="com.example.DependencyY" />
</beans>

다른 메소드는 빈 정의를으로 표시 할 수 lazy-init="true"있지만 정의는 여전히 애플리케이션 컨텍스트 내에 등록됩니다 (그리고 비정규 자동 연결을 사용할 때 삶이 더 어려워집니다). 어노테이션을 @Component통해 기반 Bean으로 프로파일을 사용할 수도 있습니다 @Profile.

Check ApplicationContextInitialier (or this example) to see how you can activate profiles programatically (i.e. based on your condition).

Java config

This is why Java based config is being so popular as you can do:

@Bean
public MyBean myBean() {
    MyBean myBean = new MyBean();
    if (true /* some condition */) {
        myBean.setDependency(dependencyX());
    } else {
        myBean.setDependency(dependencyY());
    }
    return myBean;
}

Of course you can use more or less all configuration methods in the java based config as well (via @Profile, @Value or @Qualifier + @Autowired).

Post processor

Spring offers numerous hook points and SPIs, where you can participate in the application context life-cycle. This section requires a bit more knowledge of Spring's inner workings.

BeanFactoryPostProcessors can read and alter bean definitions (e.g. property placeholder ${} resolution is implemented this way).

BeanPostProcessors can process bean instances. It is possible to check freshly created bean and play with it (e.g. @Scheduled annotation processing is implemented this way).

MergedBeanDefinitionPostProcessor is extension of bean post processor and can alter the bean definition just before it is being instantiated (@Autowired annotation processing is implemented this way).


UPDATE Oct 2015

  • Spring 4 has added a new method how to do conditional bean registration via @Conditional annotation. That is worth checking as well.

  • Of course there are numerous other ways with Spring Boot alone via its @ConditionalOn*.

  • Also note that both @Import and @ComponentScan (and their XML counterparts) undergo property resolution (i.e. you can use ${}).

ReferenceURL : https://stackoverflow.com/questions/19225115/how-to-do-conditional-auto-wiring-in-spring

반응형