简体   繁体   中英

how to load @Configuration classes in an order in spring boot

i would like to load @Configuration classes in an order. i have two configuration classes. i am having a requirement of loading my SampleProperties class before sampleconfiguration class.

I have tried the following annotations but it is not working as expected.

@AutoConfigureAfter(SampleProperties.class )
@AutoConfigureBefore(SampleConfiguration.class)

I have put my congiurations class in diff package in order to read configurations classes in an order.using @Import function, i am including my configuration classes into my application

My Main Class:

@Import({SampleProperties.class,SampleConfiguration.class,}) 
public class SampleApplication{  

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }
}

My SampleProperties Class

@Configuration
@AutoConfigureBefore(SampleConfiguration.class) 
@ConfigurationProperties("demo")
@Data
public class SampleProperties  {

    private String team;
    private int teamSize;
    private String teamLeader;

}

My sampleconfiguration Class:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef="sampleEntityManager", 
                       transactionManagerRef="sampleTransactionManager",
                       basePackages= {"com.example.demo.repo"})
@AutoConfigureAfter(SampleProperties.class)                    
public class SampleConfiguration {


    @Autowired
    Environment env;



    @Bean(name="sampleDataSource")
    @Primary
    public DataSource dmsDataSource() { 

         // functions
        return null;
    }


    @Primary
    @Bean(name = "sampleEntityManager")
    public LocalContainerEntityManagerFactoryBean dmsEntityManagerFactory(EntityManagerFactoryBuilder builder) {
      // functions
        return null;
    }

    @Primary
    @Bean(name = "sampleTransactionManager")
    public PlatformTransactionManager dmsTransactionManager(@Qualifier("sampleEntityManager") EntityManagerFactory entityManagerFactory) {
      // functions
        return null;
    }
}

can anyone tell me what missing and where am making mistakes?

I think you have to use @Order annotation.

@Component
@Order(1)
public class SampleProperties {
   // code
}

@Component
@Order(2)
public class SampleConfiguration {
    // code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM