복붙노트

[SPRING] 스프링 부트 자동 구성 순서

SPRING

스프링 부트 자동 구성 순서

나는 (조건 적으로) 하나의 bean을 생성하는 Spring Boot 자동 설정 클래스를 만들고 싶다.하지만 이것은 Spring Booting의 기본 자동 설정 클래스 중 하나에서 다른 bean B가 생성되기 전에 만들어 져야한다는 것이 문제이다. 콩 B는 A.에 의존하지 않습니다.

첫 시도는 @AutoConfigureBefore를 사용하는 것이 었습니다. 그건 내가 예상했던대로 작동하지 않았고, Dave Syer에 의한이 의견으로 판단해서는 안된다.

배경 : 앞서 언급 한 bean A는 Mongo Database를 변경하고 MongoTemplate이 생성되기 전에 발생해야합니다.

해결법

  1. ==============================

    1.B가 BeanFactoryPostProcessor를 사용하여 B 빈의 Bean 정의를 변경하면 B의 인스턴스를 A에 의존하게 할 수 있습니다.

    B가 BeanFactoryPostProcessor를 사용하여 B 빈의 Bean 정의를 변경하면 B의 인스턴스를 A에 의존하게 할 수 있습니다.

    public class DependsOnPostProcessor implements BeanFactoryPostProcessor {
    
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                    beanFactory, B.class, true, false);
            for (String beanName : beanNames) {
                BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
                definition.setDependsOn(StringUtils.addStringToArray(
                        definition.getDependsOn(), "beanNameOfB");
            }
        }
    
    }
    

    이것은 일반 스프링과 함께 작동하며 스프링 부트는 필요하지 않습니다. 자동 설정을 완료하려면 Bean을 인스턴스화하는 구성 클래스에 DependsOnPostProcessor에 대한 bean 정의를 추가해야합니다.

  2. ==============================

    2.Boot 1.3.0에는 @AutoConfigureOrder라는 새로운 주석이 있습니다. 적어도 이것이 @AutoConfiugreBefore와 같은 방식으로 작동하는지에 대해서는 아직 명확하지 않습니다.

    Boot 1.3.0에는 @AutoConfigureOrder라는 새로운 주석이 있습니다. 적어도 이것이 @AutoConfiugreBefore와 같은 방식으로 작동하는지에 대해서는 아직 명확하지 않습니다.

  3. ==============================

    3.@ hzpz의 대답을 참조하십시오. 여기에 히카리 데이터 소스의 자동 구성 전에 데이터베이스를 만드는 예제가 있습니다.

    @ hzpz의 대답을 참조하십시오. 여기에 히카리 데이터 소스의 자동 구성 전에 데이터베이스를 만드는 예제가 있습니다.

    import com.zaxxer.hikari.HikariDataSource;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.annotation.PostConstruct;
    import org.springframework.beans.factory.BeanFactoryUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.beans.factory.config.BeanDefinition;
    import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.util.StringUtils;
    
    @Configuration
    public class CreateDatabaseConfig {
    
      @Value("${spring.datasource.url}")
      private String url;
      @Value("${spring.datasource.hikari.username}")
      private String username;
      @Value("${spring.datasource.hikari.password}")
      private String password;
      @Value("${spring.datasource.hikari.catalog}")
      private String catalog;
    
      @Bean
      public static BeanFactoryPostProcessor dependsOnPostProcessor() {
        return beanFactory -> {
          String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
              beanFactory, HikariDataSource.class, true, false);
          for (String beanName : beanNames) {
            BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
            definition.setDependsOn(StringUtils.addStringToArray(
                definition.getDependsOn(), "createDatabaseConfig"));
          }
        };
      }
    
      @PostConstruct
      public void init() {
        try (
            Connection connection = DriverManager.getConnection(url, username, password);
            Statement statement = connection.createStatement()
        ) {
          statement.executeUpdate(
              "CREATE DATABASE IF NOT EXISTS `" + catalog
                  + "` DEFAULT CHARACTER SET = utf8mb4 COLLATE utf8mb4_unicode_ci;"
          );
        } catch (SQLException e) {
          throw new RuntimeException("Create Database Fail", e);
        }
      }
    }
    

    스키마와 데이터에 대한 더 많은 초기화는 data.sql과 schema.sql을 사용하여 수행 할 수있다. 85. 데이터베이스 초기화 추신. schema.sql에서 데이터베이스를 만들려고했으나 실패했습니다. 위의 예제가 작동합니다. :)

  4. from https://stackoverflow.com/questions/31692905/spring-boot-auto-configuration-order by cc-by-sa and MIT license