Search code examples
javaspringannotations

How to run a java task automatically from an external jar?


I want to generate a java jar which when included on the classpath of another project will launch a periodic task that does something in the background. This is very similar to eureka client. You include the dependency and add an annotation after which a service is started automatically to poll eureka server. How can I do that?

Edit: I got it to work using maven, following the example provided in the comments

  • github.com/shauank/spring-boot/tree/master/client (client which is having taskexecutor)
  • github.com/shauank/spring-boot/tree/master/application (Application which uses jar created in step1)

Solution

  • You can use concept of Autoconfiguration. Same is used by Eureka and Config server.

    Under src/main/resource create spring.factories and add following entry

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    location.to.your.executor
    
    

    Your class,

    pacakage location.to.your.executor
    
    class MyExecutor{
    
      public MyExecutor(){
        //Your code for task executor
      }
    
    }
    

    Now, above code can be build as jar and included into another spring boot project.

    So, when you run another jar, spring boot will look for auto configuration onto spring.factories class and load classes defined into it.