Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java Spark provide any support for dependency injection or IoC containers?

Having been in .NET, I am well versed in the support that micro web frameworks such as NancyFX and Web API have for IoC containers.

In similar frameworks in Ruby like Sinatra (NancyFX is based on Sinatra) it seems like you have the capability for dependency injection.

From what I see, because Java spark applications run as the main method, it doesn't seem like you can pass in your dependencies or IoC containers.

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}

I have a hard time understanding how a framework like this could be useful without supporting this.

If this framework doesn't, is there another lightweight framework (Spring is not lightweight from what I remember, but maybe things have changed) that does support this?

like image 506
TheJediCowboy Avatar asked Aug 19 '15 04:08

TheJediCowboy


1 Answers

Spring can be simply integrated with Spark. e.g.

public interface Spark {

  /**
   * adds filters, routes, exceptions, websockets and others
   */
   void register();

}

@Configuration
public class SparkConfiguration {

   @Autowired(required = false)
   private List<Spark> sparks = new ArrayList<>();

   @Bean
   CommandLineRunner sparkRunner() {
       return args -> sparks.stream().forEach( spark -> spark.register());
   }

}

@Component
public class HelloSpark implements Spark {

    @Autowired
    private HelloWorldService helloWorldService;

    @Override
    public void register() {
        get("/hello", (request, response) -> helloWorldService.hello() );
    }

}

You can find more on https://github.com/pmackowski/spring-boot-spark-java

like image 135
pmackowski Avatar answered Sep 27 '22 19:09

pmackowski