Search code examples
spring-bootspring-batchbatch-processingspring-boot-3

SpringBatch5 - Providing Batch "tablePrefix" name(from properties file) in @EnableBatchProcessing annotation


While migrating my application to SpringBatch5 , I see that new attributes were introduced to configure dataSource , transactionManager , tablePrefix etc in @EnableBatchProcessing annotation . I can able to provide batch "tablePrefix" in annotation like below , which is working fine.

@Configuration
@EnableBatchProcessing(dataSourceRef = "dataSourceCon" , transactionManagerRef = 
     "getTransactionManager" , tablePrefix = "ABC_BATCH_")
@RequiredArgsConstructor
public class BatchConf  {

     private final PlatformTransactionManager transactionManager;
     private final @Qualifier("dataSourceCon) DataSource dataSourceCon;
     private final ConfigurationProperties configProperties;    /// this class is annotated with @ConfiguratonProperties and having "tablePrefix" field 

 /// batch job , step   etc         
 }

I placed "tablePrefix" value in properties file and i want to take it from there instead of configuring name directly in code .I tried to register a bean with same name by returning the value which did n't worked out. can any one help!


Solution

  • You can use Spring's Expression Language (SpEL) in the tablePrefix argument of @EnableBatchProcessing. So now you have two choices:

    1. You can directly call the property. This can be done with:

      @EnableBatchProcessing(tablePrefix = "${config.tablePrefix}")
      public class BatchConf  {
          // ...
      }
      
    2. You can refer to the ConfigurationProperties bean by its name. The bean name depends on whether you use @Component or something like @EnableConfigurationProperties or @ConfigurationPropertiesScan. If you use the latter, then the bean name is formed by <prefix>-<fully qualified name> (see relevant Q&A). So you could do something like this:

      @EnableBatchProcessing(tablePrefix = "#{@'config-com.example.demo.ConfigurationProperties'.tablePrefix}")
      public class BatchConf  {
          // ...
      }
      

    In these examples I'm assuming that the prefix of your configuration properties is config.* and that your ConfigurationProperties class is located in a package called com.example.demo.

    The advantage of the first method is that it's kinda short, but it just reads the property itself and skips any default value or conversions set in your configuration properties class. The second method requires you to find the bean by its exact name, but also allows you to call any Java method.