Saturday, April 7, 2018

Spring with Spark Framework for Microservices

Recently, my team decided to use Spark to build our new REST api.  Spark seems easy with less coding.  We still wanted to use Spring for dependency injection.  We also wanted to use Tomcat as the standalone web container.  After some research, we figured out how to build the REST api with Spring, Spark and Tomcat.
Create class SpringSparkFilter which extends SparkFilter. Override method getApplication:
    @Override
    protected SparkApplication getApplication(FilterConfig filterConfig) throws ServletException {
        Class(?)[] configClasses = getConfigClasses(filterConfig);
        try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClasses)) {
            String applicationClassName = filterConfig.getInitParameter(APPLICATION_CLASS_PARAM);

            try {
                return (SparkApplication) context.getBean(Class.forName(applicationClassName));
            } catch (ClassNotFoundException e) {
                throw new ServletException(e);
            }
        }
    }
view rawSpringSparkFilter.java hosted with ❤ by GitHub
Create class MySparkApplication, which implements SparkApplication. Implement init method:
    @Override
    public void init() {
        get("/my-resource", (req, res) -) {
            return exampleService.getDate();
        });
    }
view rawMySparkApplication.java hosted with ❤ by GitHub
Configure web.xml to use SpringSparkFilter:
  (filter)
    (filter-name)SpringSparkFilter(/filter-name)
    (filter-class)com.zhentao.sparkjava.example.SpringSparkFilter(/filter-class)
    (init-param)
      (param-name)applicationClass(/param-name)
      (param-value)com.zhentao.sparkjava.example.MySparkApplication(/param-value)
    (/init-param)
    (init-param)
      (!-- Configuration locations must consist of one or more comma-delimited fully-qualified @Configuration classes --)
      (param-name)springConfigLocation(/param-name)
      (param-value)com.zhentao.sparkjava.example.SpringConfig(/param-value)
    (/init-param)
  (/filter)
view rawweb.xml hosted with ❤ by GitHub
Then either build a war file, and deploy it to tomcat or use tomcat7-maven-plugin for test run.  I usually use tomcat7-maven-plugin for fast development.  Here is the command:

mvn tomcat7:run

No comments:

Post a Comment

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...