Sunday, September 23, 2018

Angular App Integration with Spring Boot

Developing angular app is easy but deploying it in cloud environment has its own challenges. Spring boot application helps to overcome many of the cloud deployment challenges. Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". 

Angular apps can be used as static resources in a web application which uses Spring Boot. In this post I'll show you how to marry Angular App and Sprint Boot web application.

The technology stack required for building angular app are Node.js and Angular CLI. In the example I am using Gradle to build & package the web application.

Node.js is used to install the required packages and dependencies for the angular application.

Angular CLI is used to generate the boilerplate code for angular app using command line interface.

Gradle hepls to build, package the application and automates the deployments.

I am not going to explaing much in details about these tools or frameworks.

Project Structure


The anugular app source files are placed in webapp folder(src\main\webapp) within a spring boot application. The startup Application.java class is annotated with @SpringBootApplcation is placed in src\main\java\com\jsp\jsonformatter\angularboot\.

  1 
package com.jsp.jsonformatter.angularboot;
  2 
 
  3 
import org.springframework.boot.SpringApplication;
  4 
import org.springframework.boot.autoconfigure.SpringBootApplication;
  5 
 
  6 
@SpringBootApplication
  7 
public class Application {
  8 
 
  9 
    public static void main(String[] args) {
 10 
        SpringApplication.run(Application.class, args);
 11 
    }
 12 
}

Angular build configuration

The anugular application can be build using ng build and it can be executed & tested using ng serve  You need to install the required packages and dependencies using npm install The ng build or ng serve uses the angular-cli.json or angular.json to build & package the angular application.



   1 
{
   2 
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
   3 
  "version": 1,
   4 
  "newProjectRoot": "projects",
   5 
  "projects": {
   6 
    "webapp": {
   7 
      "root": "",
   8 
      "sourceRoot": "src",
   9 
      "projectType": "application",
  10 
      "prefix": "app",
  11 
      "schematics": {},
  12 
      "architect": {
  13 
        "build": {
  14 
          "builder": "@angular-devkit/build-angular:browser",
  15 
          "options": {
  16 
            "outputPath": "dist/static",
  17 
            "index": "src/index.html",
  18 
            "main": "src/main.ts",
  19 
            "polyfills": "src/polyfills.ts",
  20 
            "tsConfig": "src/tsconfig.app.json",
  21 
            "assets": [
  22 
              "src/favicon.ico",
  23 
              "src/assets"
  24 
            ],
  25 
            "styles": [
  26 
              "src/styles.scss"
  27 
            ],
  28 
            "scripts": []
  29 
          },
  30 
          "configurations": {
  31 
            "production": {
  32 
              "fileReplacements": [
  33 
                {
  34 
                  "replace": "src/environments/environment.ts",
  35 
                  "with": "src/environments/environment.prod.ts"
  36 
                }
  37 
              ],
  38 
              "optimization": true,
  39 
              "outputHashing": "all",
  40 
              "sourceMap": false,
  41 
              "extractCss": true,
  42 
              "namedChunks": false,
  43 
              "aot": true,
  44 
              "extractLicenses": true,
  45 
              "vendorChunk": false,
  46 
              "buildOptimizer": true
  47 
            }
  48 
          }
  49 
        },
  50 
        "serve": {
  51 
          "builder": "@angular-devkit/build-angular:dev-server",
  52 
          "options": {
  53 
            "browserTarget": "webapp:build"
  54 
          },
  55 
          "configurations": {
  56 
            "production": {
  57 
              "browserTarget": "webapp:build:production"
  58 
            }
  59 
          }
  60 
        },
  61 
        "extract-i18n": {
  62 
          "builder": "@angular-devkit/build-angular:extract-i18n",
  63 
          "options": {
  64 
            "browserTarget": "webapp:build"
  65 
          }
  66 
        },
  67 
        "test": {
  68 
          "builder": "@angular-devkit/build-angular:karma",
  69 
          "options": {
  70 
            "main": "src/test.ts",
  71 
            "polyfills": "src/polyfills.ts",
  72 
            "tsConfig": "src/tsconfig.spec.json",
  73 
            "karmaConfig": "src/karma.conf.js",
  74 
            "styles": [
  75 
              "src/styles.css"
  76 
            ],
  77 
            "scripts": [],
  78 
            "assets": [
  79 
              "src/favicon.ico",
  80 
              "src/assets"
  81 
            ]
  82 
          }
  83 
        },
  84 
        "lint": {
  85 
          "builder": "@angular-devkit/build-angular:tslint",
  86 
          "options": {
  87 
            "tsConfig": [
  88 
              "src/tsconfig.app.json",
  89 
              "src/tsconfig.spec.json"
  90 
            ],
  91 
            "exclude": [
  92 
              "**/node_modules/**"
  93 
            ]
  94 
          }
  95 
        }
  96 
      }
  97 
    },
  98 
    "webapp-e2e": {
  99 
      "root": "e2e/",
 100 
      "projectType": "application",
 101 
      "architect": {
 102 
        "e2e": {
 103 
          "builder": "@angular-devkit/build-angular:protractor",
 104 
          "options": {
 105 
            "protractorConfig": "e2e/protractor.conf.js",
 106 
            "devServerTarget": "webapp:serve"
 107 
          },
 108 
          "configurations": {
 109 
            "production": {
 110 
              "devServerTarget": "webapp:serve:production"
 111 
            }
 112 
          }
 113 
        },
 114 
        "lint": {
 115 
          "builder": "@angular-devkit/build-angular:tslint",
 116 
          "options": {
 117 
            "tsConfig": "e2e/tsconfig.e2e.json",
 118 
            "exclude": [
 119 
              "**/node_modules/**"
 120 
            ]
 121 
          }
 122 
        }
 123 
      }
 124 
    }
 125 
  },
 126 
  "defaultProject": "webapp"
 127 
}

Take a closer look at output path property. The outputPath is defined as dist\static. This is important as the angular app build output will be used as static resource by the Spring Boot applicaiton.

Building Together (Angular + Spring Boot App)

The Gradle build script is used to build the Spring Boot app and it will take care of building Angular app as static resource to the Spring Boot App

Take a closer at the installAngular and buildAngular task in Gradle script. The installAngular task installs the required packages & dependencies defined in package.json. It uses the npm install command to install the required pacakges.

The buildAngular task uses the "ng build" angular cli command to build the angular project. The output of angular build will be placed in dist\static folder.

  1 
buildscript {
  2 
    ext {
  3 
        springBootVersion = '1.5.4.RELEASE'
  4 
    }
  5 
    repositories {
  6 
        mavenCentral()
  7 
    }
  8 
    dependencies {
  9 
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
 10 
    }
 11 
}
 12 
 
 13 
apply plugin: 'java'
 14 
apply plugin: 'eclipse'
 15 
apply plugin: 'org.springframework.boot'
 16 
 
 17 
version = '0.0.1-SNAPSHOT'
 18 
sourceCompatibility = 1.8
 19 
 
 20 
repositories {
 21 
    mavenCentral()
 22 
}
 23 
 
 24 
 
 25 
dependencies {
 26 
    compile('org.springframework.boot:spring-boot-starter-web')
 27 
    testCompile('org.springframework.boot:spring-boot-starter-test')
 28 
}
 29 
 
 30 
def webappDir = "$projectDir/src/main/webapp"
 31 
sourceSets {
 32 
    main {
 33 
        resources {
 34 
            srcDirs = ["$webappDir/dist", "$projectDir/src/main/resources"]
 35 
        }
 36 
    }
 37 
}
 38 
 
 39 
processResources {
 40 
    dependsOn "buildAngular"
 41 
}
 42 
 
 43 
task buildAngular(type:Exec) {
 44 
    // installAngular should be run prior to this task
 45 
    dependsOn "installAngular"
 46 
    workingDir "$webappDir"
 47 
    inputs.dir "$webappDir"
 48 
    // Add task to the standard build group
 49 
    group = BasePlugin.BUILD_GROUP
 50 
    // ng doesn't exist as a file in windows -> ng.cmd
 51 
    if (System.getProperty("os.name").toUpperCase().contains("WINDOWS")){
 52 
        commandLine "ng.cmd", "build", " --prod --aot"
 53 
    } else {
 54 
        commandLine "ng", "build"
 55 
    }
 56 
}
 57 
 
 58 
task installAngular(type:Exec) {
 59 
    workingDir "$webappDir"
 60 
    inputs.dir "$webappDir"
 61 
    group = BasePlugin.BUILD_GROUP
 62 
    if (System.getProperty("os.name").toUpperCase().contains("WINDOWS")){
 63 
        commandLine "npm.cmd", "install"
 64 
    } else {
 65 
        commandLine "npm", "install"
 66 
    }
 67 
}
The buildAngular task is added as processResouces in the gradle script and the installAngular task is added as dependency to buildAngular task. The gradle build script has been modified to include the angular app's dist directory in soruceSets.

Commands to build & run

Execute the following command to build the app

gradle build

Execute the following command to run the app

gradle bootRun

:) Happy Building :)


Live JSON Formatter Demo



Download Source




47 comments:

  1. Thanks for your great and helpful presentation I like your good service. I always appreciate your post. That is very interesting I love reading and I am always searching for informative information like this. Well written article Thank You for Sharing with Us pmp training in chennai | pmp training class in chennai | pmp training near me | pmp training courses online | pmp training fee

    ReplyDelete
    Replies
    1. Developing angular app is easy but deploying it in cloud environment has its own challenges. Spring boot application helps to overcome many of the cloud deployment challenges. Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".

      Angular apps can be used as static resources in a web application which uses Spring Boot. In this post I'll show you how to marry Angular App and Sprint Boot web application.

      The technology stack required for building angular app are Node.js and Angular CLI. In the example I am using Gradle to build & package the web application.

      major project for cse final year

      Final Year Project Centers in Chennai

      IEEE projects for cse

      Delete
  2. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.

    machine learning classroom training in chennai
    machine learning certification in chennai
    top institutes for machine learning in chennai
    Android training in velachery
    PMP training in chennai

    ReplyDelete
  3. Nice blog..! I really loved reading through this article. Thanks for sharing such a amazing post with us and keep blogging... best angularjs training institute in chennai | angularjs training in omr | angularjs training in chennai | angularjs best training center in chennai

    ReplyDelete
  4. This concept is a good way to enhance the knowledge.thanks for sharing. please keep it up machine learning certification

    ReplyDelete

  5. I am a new user of this site so here i saw multiple articles and posts posted by this site,I curious more interest in some of them hope you will give more information on this topics in your next articles.
    ExcelR business analytics courses

    ReplyDelete
  6. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
    data analytics course mumbai

    ReplyDelete
  7. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
    data analytics course mumbai

    ReplyDelete
  8. Hi! This is my first visit to your blog! We are a team of volunteers and new initiatives in the same niche. Blog gave us useful information to work. You have done an amazing job!data science course in malaysia
    best tableau training
    data analytics course malaysia
    360DigiTMG

    ReplyDelete
  9. Thanks for this blog are more informative contents step by step. I here attached my site would you see this blog.

    7 tips to start a career in digital marketing

    “Digital marketing is the marketing of product or service using digital technologies, mainly on the Internet, but also including mobile phones, display advertising, and any other digital medium”. This is the definition that you would get when you search for the term “Digital marketing” in google. Let’s give out a simpler explanation by saying, “the form of marketing, using the internet and technologies like phones, computer etc”.

    We have offered to the advanced syllabus course digital marketing for available join now.

    more details click the link now.

    https://www.webdschool.com/digital-marketing-course-in-chennai.html

    ReplyDelete
  10. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.
    PMP Certification

    PMP Certification in malaysia


    360DigiTMG

    ReplyDelete
  11. It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it!

    PMP Course in Malaysia

    ReplyDelete
  12. A debt of gratitude is in order for sharing the information, keep doing awesome... I truly delighted in investigating your site. great asset...
    data science certification

    ReplyDelete
  13. It's late finding this act. At least, it's a thing to be familiar with that there are such events exist. I agree with your Blog and I will be back to inspect it more in the future so please keep up your act.
    PMP Certification
    PMP Course
    PMP Course in Malaysia
    PMP training in Malaysia
    PMP Training

    ReplyDelete
  14. If your looking for Online Illinois license plate sticker renewals then you have need to come to the right place.We offer the fastest Illinois license plate sticker renewals in the state.
    data science course

    ReplyDelete
  15. Daily visits listed here are the best way to appreciate your energy and that's why I go to the website every day, searching for new, interesting stuff. Thanks so much! 360DigiTMG data scientist course in malaysia

    ReplyDelete
  16. Plumbing & HVAC Services San Diego
    Air Star Heating guarantees reliability and quality for all equipment and services.
    Air Star Heating is specializing in providing top-quality heating, ventilating, air conditioning, and plumbing services to our customers and clients.
    Our company is leading the market right now. By using our seamless and huge array of services. Our customers can now have the privilege of taking benefit from our services very easily and swiftly. To cope up with the desires and needs of our clients we have built an excellent reputation. We are already having a huge list of satisfied customers that seem to be very pleased with our services.

    Plumbing & HVAC Services in San Diego. Call now (858) 900-9977 ✓Licensed & Insured ✓Certified Experts ✓Same Day Appointment ✓Original Parts Only ✓Warranty On Every Job.
    Visit:- https://airstarheating.com

    ReplyDelete
  17. Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better! Cheers, keep doing awesome! Jacob

    ReplyDelete
  18. Excellent website. I was always checking this article, and I’m impressed! Extremely useful and valuable info specially the last part, I care for such information a lot. Thanks buddy.
    Data Science Training in Hyderabad
    Data Science Course in Hyderabad

    ReplyDelete
  19. Excellent post. I want to thank you for this informative read, I really appreciate sharing this great post. Keep up your work.
    DevOps Training in Hyderabad
    DevOps Course in Hyderabad

    ReplyDelete
  20. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.
    ServiceNow Training in Pune

    ReplyDelete
  21. I would like to thank you for the efforts you had made for writing this information. This article inspired me to read more. keep it up
    servicenow training in Bangalore

    ReplyDelete
  22. Good Post! it was so good to read and useful to improve my knowledge as an updated one, keep blogging.
    servicenow training in Bangalore

    ReplyDelete
  23. The information you have posted is very useful. The sites you have referred was good. Thanks for sharing.
    ServiceNow Training in Pune

    ReplyDelete
  24. Thank You for providing us with such an insightful information through this blog.
    ServiceNow Training in Pune

    ReplyDelete
  25. Place a wager on any 메리트카지노 considered one of these fabulous gaming choices, and you could very well turn into the large winner of the day. Our bonuses and promotions supply many extra cause why} you should to} enroll at Jazzy Spins. Our welcome bonus alone may get you a hefty amount of money in your participant account, enabling you to play and win at our video games. Many extra bonuses and promotions are supplied on a regular basis|regularly|frequently}, so {you have|you've|you may have} much more probabilities of profitable.

    ReplyDelete
  26. Among different issues, guests will discover a daily dose of articles with the most recent poker 원 엑스 벳 information, reside reporting from tournaments, unique movies, podcasts, reviews and bonuses and so much more. If you cease the slot machine, you can to|you possibly can} scale back the TOS to a few seconds. They are laser-focused on their recreation and their rapid-fire of button hits certainly one of the|is among the|is probably certainly one of the} most repetitive and well-timed actions in the complete on line casino. You discover a full listing of all the online casinos allowed in your nation on this page. Instead of focusing on the generic tips and tips you discover on all on line casino guides on the web, it focuses on confirmed methods to improve your odds when you choose the games to play.

    ReplyDelete
  27. รีวิวเกมส์ loki789 หากไม่มีข้อมูลอื่นที่เกี่ยวข้องแล้ว pg slot สามารถติดต่อเจ้าหน้าที่สนับสนุนของผู้ให้บริการเกมนั้น ๆ เพื่อขอข้อมูลเพิ่มเติมเกี่ยวกับชื่อเล่นและข้อมูลผู้ใช้งาน loki789

    ReplyDelete
  28. This blog post is an insightful guide on integrating Angular with Spring Boot, addressing a common challenge for developers working with cloud deployments. The clear explanation of how Spring Boot can simplify cloud deployments while serving Angular apps as static resources is particularly valuable.

    The post effectively outlines the technology stack required—Node.js, Angular CLI, and Gradle—and explains their roles succinctly. While the post doesn’t delve deeply into each tool, it provides a solid overview of how they fit into the overall process.

    The mention of placing Angular app source files within the webapp folder of a Spring Boot project and the use of Gradle for building and packaging adds practical clarity for readers. The inclusion of the project structure and the specific location of the Application.java class in the directory is helpful for anyone setting up a similar project.

    Overall, this post is a useful resource for developers looking to streamline their Angular and Spring Boot integration, and the hands-on approach makes it an excellent starting point for implementing these technologies together.
    data analytics courses in dubai

    ReplyDelete
  29. What a valuable resource for budding data scientists! The thorough breakdown of courses is fantastic. I’m excited to explore these data science courses in Faridabad soon. Thanks for the info!

    ReplyDelete
  30. Great job on tackling the integration of Angular with Spring Boot! It’s a powerful combination for building full-stack applications, and your clear explanation makes it approachable. Keep sharing such practical insights—it really helps others bridge the gap between front-end and back-end development!
    Data Science Courses in Singapore

    ReplyDelete
  31. This blog post was a delight! Your insights are always so refreshing and thought-provoking. Thank you for sharing your knowledge!

    Data science courses in Gujarat

    ReplyDelete
  32. "Great tutorial! I really appreciate how you explained the integration between Angular and Spring Boot step by step. The code snippets are super helpful for visual learners like me. This will definitely streamline my development process. Thanks for sharing such valuable insights!"
    Data science courses in Bhutan

    ReplyDelete
  33. AN excellent blog shared on angular integration. Thanks for enlightening.
    Data Science Courses in Hauz Khas

    ReplyDelete
  34. "I’m really intrigued by the Data Science Course in Dadar!
    The detailed curriculum is impressive and covers a lot of ground.
    I appreciate the focus on hands-on learning, which is so crucial.
    This could be a great chance to enhance my skills in the field.
    I can’t wait to explore enrollment options!"

    ReplyDelete
  35. "I took IIM Skills’ Data science while living in Mumbai, and it has been fantastic. The online format fits seamlessly into my schedule."

    ReplyDelete
  36. This is a great overview of integrating Angular with Spring Boot! Your explanation of how Spring Boot simplifies cloud deployment challenges while allowing Angular apps to be served as static resources is really insightful. Data science courses in Mysore

    ReplyDelete
  37. You’ve explained Angular App Integration with Spring Boot
    in such a simple, clear way. I’m definitely going to try out these tips. Thanks for step by step guide.
    Data Science Courses in China


    ReplyDelete
  38. "Excellent post! Your explanation of integrating Angular with Spring Boot is clear and easy to follow. It’s a great guide for anyone working on full-stack development. Thanks for sharing such a useful resource!"

    Data science courses in Bangladesh

    ReplyDelete
  39. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
    IIM SKILLS Data Science Course Reviews

    ReplyDelete
  40. Great read! I really enjoyed the insights shared in this post. It's clear a lot of thought went into it, and the information was really helpful. Looking forward to reading more content like this. Keep up the great work!
    GST Course

    ReplyDelete
  41. Great tutorial on integrating Angular with Spring Boot! It's a practical approach to deploying Angular apps as static resources in a Spring Boot web application. Using Gradle to automate the build and deployment process is a smart choice for managing both backend and frontend efficiently. This setup is definitely useful for cloud environments where seamless integration between the frontend and backend is crucial. Investment Banking Course

    ReplyDelete