The document discusses Spring Boot, a framework for creating stand-alone, production-grade Spring based applications. It describes how Spring Boot allows creating projects quickly with features like embedded servers and auto-configuration. It then covers how to develop a basic Spring Boot web application including creating the project structure with Maven, adding controllers and properties files, and connecting to databases using Spring Data. Overall, the document provides an overview of Spring Boot and guidance on starting a Spring Boot web application project.
Spring Boot allows creating standalone Spring applications with minimal configuration. It makes assumptions about dependencies and provides default configurations. It aims to provide a faster development experience for Spring. Some key Spring Boot components include auto-configuration, core functionality, CLI, actuator for monitoring, and starters for common dependencies. To use Spring Boot, create a project with the Spring Initializr, add code and configurations, then build a jar file that can be run standalone.
This is a basic tutorial on Spring core.
Best viewed when animations and transitions are supported, e.g., view in MS Powerpoint. So, please try to view it with animation else the main purpose of this presentation will be defeated.
This document discusses Spring Boot and how it provides automatic configuration for common web application functionalities like JPA, security, and Spring MVC. It also covers how Spring Boot uses starter dependencies to select libraries automatically and provides tools like the CLI and Spring Initializr. The document then demonstrates creating a basic Spring Boot application and discusses testing Spring Boot applications using techniques like mocking Spring MVC and integrating tests.
The document provides an overview and introduction to Spring Data JPA, including:
1) How Spring Data abstracts away basic data management concepts and supports both relational and non-relational databases.
2) An example of refactoring from plain JPA to Spring Data JPA by defining a repository interface and using built-in query methods.
3) How the Spring Data repository abstraction reduces the effort to implement data access layers through interfaces like Repository.
This document contains an agenda and slides for a presentation on Spring Boot. The presentation introduces Spring Boot, which allows developers to rapidly build production-grade Spring applications with minimal configuration. It demonstrates how to quickly create a "Hello World" application using Spring Boot and discusses some of the features it provides out-of-the-box like embedded servers and externalized configuration. The presentation also shows how to add additional functionality like Thymeleaf templates and actuator endpoints to monitor and manage applications.
Spring Boot is a framework for creating stand-alone, production-grade Spring-based applications that can be started using java -jar without requiring any traditional application servers. It is designed to get developers up and running as quickly as possible with minimal configuration. Some key features of Spring Boot include automatic configuration, starter dependencies to simplify dependency management, embedded HTTP servers, security, metrics, health checks and externalized configuration. The document then provides examples of building a basic RESTful web service with Spring Boot using common HTTP methods like GET, POST, PUT, DELETE and handling requests and responses.
Presentation provides introduction and detailed explanation of the Java 8 Lambda and Streams. Lambda covers with Method references, default methods and Streams covers with stream operations,types of streams, collectors. Also streams are elaborated with parallel streams and benchmarking comparison of sequential and parallel streams.
Additional slides are covered with Optional, Splitators, certain projects based on lambda and streams
This document discusses data access with JDBC using the Spring Framework. It covers Spring's DAO support, exception handling, and approaches for database access including JdbcTemplate, NamedParameterJdbcTemplate, and controlling connections through a DataSource. The core classes provided by Spring simplify JDBC usage and handle common database tasks like opening/closing connections and transactions.
JQuery is a JavaScript library that simplifies HTML document manipulation, event handling, animations, and Ajax interactions. It works across browsers and makes tasks like DOM traversal and manipulation, event handling, animation, and Ajax much simpler. JQuery's versatility, extensibility, and cross-browser compatibility have made it popular, with millions of developers using it to write JavaScript.
The document discusses several core Java concepts including:
1) Comments in Java code can be single-line or multiline javadoc comments.
2) Classes are fundamental in Java and describe data objects and methods that can be applied to objects.
3) Variables and methods have scopes determined by curly braces and a variable is only available within its scope.
This document provides an overview of developing a web application using Spring Boot that connects to a MySQL database. It discusses setting up the development environment, the benefits of Spring Boot, basic project structure, integrating Spring MVC and JPA/Hibernate for database access. Code examples and links are provided to help get started with a Spring Boot application that reads from a MySQL database and displays the employee data on a web page.
This document discusses React component lifecycle methods and the different phases a component goes through: initialization, mounting, updating, and unmounting. It provides details on the purpose and usage of each lifecycle method, including the constructor, componentWillMount, render, componentDidMount, componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, componentDidUpdate, and componentWillUnmount. The lifecycle methods allow performing actions at specific stages of the component's existence, such as initializing state, integrating APIs, updating based on new props or state, and cleaning up.
Introduction to the Spring Framework:
Generar description
IoC container
Dependency Injection
Beans scope and lifecycle
Autowiring
XML and annotation based configuration
Additional features
This presentation introduces some advanced concepts of generics in Java. These slides introduce the following concepts:
- Generic classes and methods
- Type variable bounds
- Type erasure process
- Generics and inheritance
- Wildcard types
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
Hibernate is an object-relational mapping tool that allows developers to more easily write applications that interact with relational databases. It does this by allowing developers to map Java classes to database tables and columns, so that developers can interact with data through Java objects rather than directly with SQL statements. Hibernate handles the conversion between Java objects and database rows behind the scenes. Some key benefits of using Hibernate include faster data retrieval, avoiding manual database connection management, and easier handling of database schema changes.
React JS is a JavaScript library for building user interfaces. It uses virtual DOM and one-way data binding to render components efficiently. Everything in React is a component - they accept custom inputs called props and control the output display through rendering. Components can manage private state and update due to props or state changes. The lifecycle of a React component involves initialization, updating due to state/prop changes, and unmounting from the DOM. React promotes unidirectional data flow and single source of truth to make views more predictable and easier to debug.
This document provides an overview of React including:
- React is a JavaScript library created by Facebook for building user interfaces
- It uses virtual DOM to efficiently re-render components on updates rather than entire page
- React supports ES6 features and uses classes, arrow functions, and other syntax
- Popular tools for React include Create React App for setting up projects and React Dev Tools for debugging
Spring boot is a great and relatively a new project from Spring.io. The presentation discusses about basics of spring boot to advance topics. Sample demo apps are available here : https://github.com/bhagwat/spring-boot-samples
This session will be about maintaning the store on client side with redux, And will have more details about state management addressing single source of truth concept
The document discusses different approaches to object-oriented programming in JavaScript, including classical and prototypal inheritance, constructor functions, and the prototype property. It explains how prototypal inheritance works by linking objects together through their internal prototype properties. Constructor functions and the new operator allow simulating classical inheritance by establishing prototype links. Various design patterns are also covered, such as public/privileged methods, singletons, modules, and parasitic inheritance.
The document discusses Spring Boot, a framework that makes it easier to create production-grade Spring-based applications. It provides auto-configuration, opinionated defaults that minimize configuration, and the ability to create standalone applications. Key topics covered include Spring Boot's goals of reducing complexity and development time, its use of auto-configuration and starters to simplify dependency management, and how it allows applications to run independently without external servers.
Spring Boot is a framework for developing Java applications that reduces configuration and provides production-ready features. It allows developing Spring applications with minimal configuration by automatically configuring Spring and third-party libraries. Spring Boot provides starter dependencies to simplify build configuration and modules for autoconfiguration, CLI, monitoring, and more.
Building a Spring Boot Application - Ask the Audience! (from JavaLand 2017)🎤 Hanno Embregts 🎸
Spring Boot makes it easy to create stand-alone Spring-based application that you can 'just run'. It uses a 'convention over configuration' approach to get you up and running in no-time, while offering all Spring features that you have grown fond of in the past years. In this session this is demonstrated by live-coding a Spring Boot application that will just work.
But audience beware, this is not your standard live-coding session'. Attendees will have a vital say in the session's content by defining the applications requ irements. Should it be an app to track your kitchen cupboard contents or do you want a simple task planner? It's up to you! Should it use MongoDB or Couchbase? You decide! Do you want an AngularJS front-end with a RESTful backend or do you prefer a classic web app with Thymeleaf templates? It's your call! Seriously.
During the session you get to make these decisions by participating in an online vote. And you will discover that Spring Boot is up to the task no matter what choices you make.
So what are you waiting for? Bring your own device, help shape the application that we're building and learn lots about Spring Boot in the process.
This session is intended for Java software engineers with an interest in Spring Boot. Some Spring experience could come in handy, but is not strictly necessary. After this session, you will know enough to start your own Spring Boot project.
Building a Spring Boot Application - Ask the Audience! (from JVMCon 2018)🎤 Hanno Embregts 🎸
Spring Boot is a framework for creating stand-alone, production-grade Spring based applications that can be "run" using java -jar without the need for an external web server. It favors convention over configuration and aims to get developers up and running quickly with minimal configuration. Key features include an embedded web server, automatic configuration, and starters that provide prepackaged dependencies. Pros include faster development and deployment, while potential cons include more complex custom configuration and incompatibility with some legacy Spring projects. The documentation provides guidance on creating starter projects with an initial Java file, build script, and dependencies.
Spring Boot is an open source Java-based framework that makes it easy to create stand-alone, production-grade Spring based Applications. It provides features such as embedded HTTP servers, externalized configuration, and metrics. Spring Boot uses auto-configuration and starters to minimize configuration work. The main intention of Spring Boot starters is to combine common dependencies into single dependencies to simplify dependency management. Spring Boot also provides auto-configuration to avoid explicit configuration of components like views and ViewResolvers.
Building a Spring Boot Application - Ask the Audience!🎤 Hanno Embregts 🎸
This document provides an overview of building applications with Spring Boot. It discusses key features such as creating stand-alone Spring applications without separate web servers, automatic Spring configuration, and getting started quickly with one Java file and a build script. Pros include faster deployments and no need for web.xml files. Cons can include custom configuration challenges and incompatibility with some legacy Spring projects. The document also demonstrates sample code and references Spring Initializr for project setups.
Spring data jpa are used to develop spring applicationsmichaelaaron25322
Spring Data JPA helps overcome limitations of JDBC API and raw JPA by automatically generating data access code. It reduces boilerplate code through repository interfaces that expose CRUD methods. The programmer defines database access methods in repository interfaces rather than implementing them, avoiding inconsistency. A Spring Data JPA project contains pom.xml, Spring Boot starters, application.properties, and main class annotated with @SpringBootApplication to run the application.
A complete boot camp for beginners who want to learn Spring Boot.
In this course, you'll learn how we can create web services and cover all the topics of Spring Boot, Spring Framework, and many others.
If you've some experience in Java and want to be a Software Engineer or Java Developer using Spring, you're on right way.
Just read and practice, in the end of this course you'll have a great knowledge of Spring boot, a backend knowledge.
Course outline:
JPA, Hibernate, Spring, Spring Framework, H2 Database, PostgreSQL, MySQL.
#SpringBoot
#SpringFramwork
#MySQL
#PostgreSQL
#MySQL
#H2
#JPA/Hibernate
#Webservices
Spring Boot provides a convention-over-configuration approach for building stand-alone, production-grade Spring-based Applications that you can "just run". It takes an opinionated view of configuring Spring applications and applications can be started using a single command. Spring Boot Actuator provides production-ready features to monitor and manage applications with no additional coding required.
This presentation will explain about spring and hibernate integration based on Java config. moreover, this presentation has a detailed explanation of spring and hibernate integration.
Welcome to presentation on Spring boot which is really great and relatively a new project from Spring.io. Its aim is to simplify creating new spring framework based projects and unify their configurations by applying some conventions. This convention over configuration is already successfully applied in so called modern web based frameworks like Grails, Django, Play framework, Rails etc.
This document discusses Spring Boot, an open source framework for building microservices and web applications. It provides scaffolding to help build Spring-based services more quickly. The author chose Spring Boot for a project because it integrates well with other frameworks like Jersey and allows building services quickly. Key Spring Boot components discussed include REST frameworks, embedded servers, logging frameworks, security, and metrics. The author outlines their Spring Boot stack and package structure. They discuss using Spring Data for persistence, Swagger for API documentation, and helper libraries like Lombok. The document also covers testing approaches using REST Assured and Spring Integration.
Springboot2 postgresql-jpa-hibernate-crud-example with testHyukSun Kwon
This document discusses how to configure Spring Boot, Spring Data JPA, and PostgreSQL to build a RESTful API for managing employee data. It includes setting up dependencies, creating JPA entities and repositories, developing controllers, handling exceptions, running integration tests, and more. Key steps are to add PostgreSQL and Spring Data JPA dependencies, configure the database connection properties, develop the Employee entity and repository, create REST controllers to expose CRUD operations, and write integration tests using TestRestTemplate to test the API endpoints.
Spring Boot provides an easy way to create stand-alone, production-grade Spring based applications that you can "just run". It takes an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Some key features include embedded Tomcat/Jetty so no need to deploy WAR files, automatic configuration, starter POMs to simplify dependency management. This document discusses setting up a development environment for Spring Boot, creating a basic app, connecting to a database using JPA, and packaging into a runnable JAR file or WAR deployable to Tomcat.
Spring Boot is an open-source Java-based framework. Spring Boot is a utility for setting up an application quickly by automating the configuration procedures and speed up the process of building and deploying Spring Boot applications. It is easy to create production-ready applications using Spring Boot through embedded server(tomcat).
This document provides an overview of Spring Boot, a framework for creating stand-alone, production-grade Spring based applications. It discusses how Spring Boot aims to make it easy to create Spring applications with default configurations and minimal code. The key topics covered include: using Maven and Gradle build tools with Spring Boot, common features and conventions like auto-configuration and main application classes, Spring Data and JPA for database access, Spring MVC features for web applications, and testing Spring applications.
Spring Boot is a framework that makes it easy to create stand-alone, production-grade Spring based applications that you can "just run". It allows you to create stand-alone applications, embed Tomcat/Jetty directly with no need to deploy WAR files, and provides starter POMs to simplify configuration. Spring Boot applications are run by adding a spring-boot-gradle-plugin and can then be run as an executable JAR. Features include REST endpoints, security, external configuration, and production monitoring via Actuators.
Top 10 Spring Boot Interview Questions and Answersnarendrachinnu
Spring Boot makes it easier to create production-ready Spring applications with default configurations and by avoiding boilerplate code. It provides starters that include common dependencies and allows overriding default properties through an application.properties file. Spring Boot also includes an embedded server and DevTools for faster development. While it speeds up development, converting existing Spring applications may be time-consuming. Spring Boot works exclusively with Spring projects and requires the use of Java.
This document provides an overview and introduction to Spring Boot. It discusses:
- The goals of Spring Boot to provide a faster setup process and default configurations without needing XML.
- Key features like auto-configuration, embedded servlet containers, and the use of starters for common dependencies.
- Conventions for project structure, main application classes, and defining beans.
- How to configure databases, implement JPA repositories, and build REST APIs with Spring MVC and data REST.
- Tips for testing Spring applications and building executable JAR files for deployment.
This document provides an overview and introduction to Spring Boot. It discusses:
- The goals of Spring Boot to provide a faster setup process and default configurations without needing XML.
- Key features like auto-configuration, embedded servlet containers, and the use of starters for common dependencies.
- Conventions in Spring Boot for project structure, main classes, configuration properties, and more.
- How to set up a Spring Boot project using Maven, including using the spring-boot-starter-parent and starter POMs.
- Support in Spring Boot for Spring MVC, data access with JPA/Spring Data, REST services, and testing.
This article is about aspect oriented programming (aop) in spring. the related example of an application with aop support is in the following address :
https://github.com/ghorbanihamid/SpringBoot_AOP_JPA_Example
The Spring Framework provides a comprehensive Java platform for developing applications. It simplifies development by allowing developers to avoid dealing directly with complex APIs. Spring uses Inversion of Control and Dependency Injection to decouple classes and increase maintainability. The core Spring modules include beans, context, AOP, and aspects. Spring MVC implements the MVC pattern to build web applications, separating the model, view, and controller aspects.
Tokenization is a technology used by banks to protect customer data from fraud. It involves substituting sensitive data with unique, non-sensitive tokens. This makes the data less useful to hackers if accessed without context. Tokenization protects data during transactions more effectively than encryption alone by not requiring decryption of sensitive details that could be exposed. Common payment attacks like relay attacks that steal data during transactions cannot be used with tokenized data since the token cannot be used outside of its intended transaction.
1) Single page applications (SPAs) use JavaScript to dynamically update the content of a single web page rather than loading entire new pages. This reduces page refreshes.
2) React is a popular JavaScript library for building user interfaces, especially for SPAs. It uses a virtual DOM for faster rendering.
3) Create-React-App is a command line interface that sets up a React project with common dependencies like Babel and Webpack preconfigured.
Web services can be accessed over a network and are called using HTTP. There are two main types: SOAP uses XML and is language/platform independent; REST uses URI to expose resources and can use JSON. Java has JAX-WS for SOAP and JAX-RS for RESTful services. REST is faster and uses less bandwidth than SOAP. The document discusses implementing REST services in Java using JAX-RS and Jersey, including using annotations and returning Response objects.
The document discusses inheritance in Java. It defines inheritance as a process where one class acquires properties of another class. The class that inherits properties is called a subclass, and the class whose properties are inherited is called a superclass. In Java, a subclass can only inherit from one superclass (single inheritance). The extends keyword is used for inheritance. The document then discusses what can be done in subclasses, such as overriding and overloading methods, and polymorphism. It also covers abstract classes, interfaces, and casting objects.
The document discusses various Java I/O streams including input streams, output streams, byte streams, character streams, buffered streams, properties class, print stream, file locking, serialization and print writer class. It provides examples of reading and writing files using FileInputStream, FileOutputStream, FileReader, FileWriter and other stream classes. Methods of different stream classes are also explained along with their usage.
Threads allow multiple tasks to run concurrently within a single process. Each thread has its own call stack and shares resources like memory with other threads in the same process. There are two main ways to implement threads in Java - by extending the Thread class or implementing the Runnable interface. Synchronization is needed when multiple threads access shared resources to prevent data corruption. Common methods like start(), join(), sleep() and priority help control thread execution and behavior.
Java reflection allows inspecting and modifying runtime behavior by examining classes, interfaces, and objects. It can get class information even if the class is not accessible at compile time. Some uses of reflection include IDEs, debuggers, and test tools. Reflection has drawbacks like poor performance and security issues. To use reflection, you first get the Class object using the .class syntax, getClass() method, or forName() method. With the Class object you can inspect fields, methods, constructors, modifiers, and more. Arrays are also supported through the Array class.
The Java Collections Framework provides classes and interfaces that help store and manipulate collections of objects. The main collection interfaces are List, Set, and Map. Lists allow duplicate elements and access by index. Common List implementations are ArrayList and LinkedList. Sets do not allow duplicates. Common Set implementations are HashSet, LinkedHashSet, and TreeSet. Maps store objects in key-value pairs and cannot have duplicate keys. Common Map implementations are HashMap, TreeMap, and LinkedHashMap.
Java was created in 1991 by James Gosling, Mike Sheridan, and Patrick Naughton at Sun Microsystems. It has three editions: Java ME for limited devices, Java SE as the core platform for desktops and servers, and Java EE for large enterprise applications. Java code is compiled into bytecode that runs on a Java Virtual Machine (JVM) making Java portable across platforms. Key principles of Java include being object-oriented, secure, and platform independent.
The document discusses different architectures for integrating IT systems, including point-to-point, hub-and-spoke, and enterprise service bus (ESB). It describes the core capabilities of an ESB architecture, such as adapters, message transformation, routing, security, and monitoring. Examples of ESB products are provided at different levels, from integration frameworks to full-featured ESBs.
The document discusses enterprise application integration (EAI) and enterprise service bus (ESB) architectures. It begins by explaining the challenges of integrating different IT systems, before defining EAI as an approach to interconnect disparate enterprise applications. Three common EAI approaches are then described: point-to-point integration, hub-and-spoke integration, and the ESB framework. The document dives deeper into each approach and their limitations. It then provides details on key ESB concepts like message-oriented middleware, core capabilities, patterns, and components. The relationship between ESB and service-oriented architecture (SOA) is also explained.
A captivating AI chatbot PowerPoint presentation is made with a striking backdrop in order to attract a wider audience. Select this template featuring several AI chatbot visuals to boost audience engagement and spontaneity. With the aid of this multi-colored template, you may make a compelling presentation and get extra bonuses. To easily elucidate your ideas, choose a typeface with vibrant colors. You can include your data regarding utilizing the chatbot methodology to the remaining half of the template.
Explore the rapid development journey of TryBoxLang, completed in just 48 hours. This session delves into the innovative process behind creating TryBoxLang, a platform designed to showcase the capabilities of BoxLang by Ortus Solutions. Discover the challenges, strategies, and outcomes of this accelerated development effort, highlighting how TryBoxLang provides a practical introduction to BoxLang's features and benefits.
Major Outages in Major Enterprises Payara ConferenceTier1 app
In this session, we will be discussing major outages that happened in major enterprises. We will analyse the actual thread dumps, heap dumps, GC logs, and other artifacts captured at the time of the problem. After this session, troubleshooting CPU spikes, OutOfMemoryError, response time degradations, network connectivity issues, and application unresponsiveness may not stump you.
Drona Infotech is one of the best Mobile App Development Company in Noida. Elevate your business with our professional app development services. Let us help you create user-friendly and high-performing mobile applications.
Visit Us For: https://www.dronainfotech.com/mobile-application-development/
Ansys Mechanical enables you to solve complex structural engineering problems and make better, faster design decisions. With the finite element analysis (FEA) solvers available in the suite, you can customize and automate solutions for your structural mechanics problems and parameterize them to analyze multiple design scenarios. Ansys Mechanical is a dynamic tool that has a complete range of analysis tools.
1. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
Spring Boot
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you
can "just run". The main goal of Spring Boot Framework is to reduce Development. Spring Boot is
compatible with Apache Maven 3.2 or above and Gradle 4.
you can use start.spring.io to generate a basic project.
Features:
Create stand-alone Spring applications
Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
Provide opinionated 'starter' POMs to simplify your Maven configuration
Automatically configure Spring whenever possible
Provide production-ready features such as metrics, health checks and externalized configuration
Absolutely no code generation and no requirement for XML configuration
As of Spring Framework 5.0, Spring requires JDK 8+ (Java SE 8+). Spring requires the Java EE 7 level
(e.g. Servlet 3.1+, JPA 2.1+) as a minimum - while at the same time providing out-of-the-box integration
with newer APIs at the Java EE 8 level (e.g. Servlet 4.0, JSON Binding API) when encountered at
runtime. This keeps Spring fully compatible with e.g. Tomcat 8 and 9, WebSphere 9, and JBoss EAP 7.
Spring Boot CLI:
Spring Boot ships with a command line tool allows you to run Groovy scripts. Follow the instructions
in install the Spring Boot CLI. Spring Boot does not require any special tools integration, so you can use any
IDE or text editor. Also, there is nothing special about a Spring Boot application, so you can run and
debug a Spring Boot application as you would any other Java program.
You can use Spring Boot in the same way as any standard Java library. To do so, include the
appropriate spring-boot-*.jar files on your classpath.
2. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
Developing Spring Boot web application:
For developing a spring boot web application do the following steps:
Creating a pom.xml:
We need to start the project by creating a Maven pom.xml file. The pom.xml is the recipe that is
used to build your project. There are 3 key points in pom.xml as shown below:
3. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
1) ParentTag: To create a Spring Boot application, you first need to configure the spring-boot-
starter-parent artifact in the parent section of the pom.xml. This way, you only need to
specify the dependency version once for the parent. The value is then used to determine
versions for most other dependencies – such as Spring Boot starters, Spring projects or common
third-party libraries. Parent Poms allow you to manage the following things for multiple child
projects and modules:
Configuration : Java Version and Other Properties
Depedency Management : Version of dependencies
Default Plugin Configuration
The advantage of this approach is that it eliminates potential errors related to incompatible
library versions. When you need to update the Boot version, you only need to change a
single, central version, and everything else gets implicitly updated.
2) Dependencies Tag: The dependency provides the capability to manipulate jars in the
project. These dependencies are required to compile and run the application. Spring Boot
provides a set of convenient dependency descriptors, called starters, which we can include in our
application. For example, if we want to get started using Spring and JPA for database access,
just include the spring-boot-starter-data-jpa dependency in your project. You do not need to
provide a version for any of these dependencies in your build configuration as Spring Boot is
managing that for you. When you upgrade Spring Boot itself, these dependencies will be
upgraded as well in a consistent way.
Starter should follow a naming pattern like: spring-boot-starter-*, where * is a particular type
of application. For Example:
Starter Name Description
spring-boot-starter-web
Used for building web, including RESTful, applications using Spring MVC.
Uses Tomcat as the default embedded container.
spring-boot-starter-jdbc
Used for JDBC with the Tomcat JDBC connection pool.
spring-boot-starter-mail
Used to support Java Mail and Spring Framework's email sending.
spring-boot-starter-aop
used for aspect-oriented programming with Spring AOP and AspectJ.
3) Build Tag:This element is for configuring Build plugins.
4. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
create a main class for application:
All Spring Boot applications have an entry point that works just like an ordinary Java program. It
has a main method and everything. Your application is started by executing this class. The class
must be annotated with @SpringBootApplication.
The SpringApplication class provides a convenient way to bootstrap a Spring application that is
started from a main() method. In many situations, you can delegate to the
static SpringApplication.run method, as shown in the following example:
@SpringBootApplication
public class SpringBootWebApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootWebApplication.class, args);
}
}
@SpringBootApplication is equivalent to using all of the following annotations:
@Configuration: makes the class as a source of bean definitions for the application context.
@EnableAutoConfiguration: will scan the main package and its sub packages when
executing the spring boot auto configuration feature for class path dependencies.
@EnableWebMvc: Spring Boot adds this annotation automatically when it sees spring-
webmvc on the classpath.This flags the application as a web application and activates key
behaviors such as setting up a DispatcherServlet.
@ComponentScan: tells Spring to look for other components, configurations, and services
in the default package, allowing it to find the controllers.If specific packages are not
defined, scanning will occur from the package of the class that declares this annotation.
NOTE: If you want to get the maximum advantage of spring boot’s auto configuration feature, it is
expected to put all your class packages under spring boot main application package (directly in main
package or indirectly as sub packages). If any class or package that is outside from the main application
package and it is required for completing auto configuration for some dependency, then should be
declared in the main configuration class properly with related annotation.
5. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
create a controller class:
@Controller
public class WelcomeController {
@RequestMapping("/")
public String welcome(Map<String, Object> model) {
model.put("message", "Hello World");
return "welcome";
}
}
As request first goes to dispatcherServlet and it redirects to the controller class. Here
@Controller depicts that this is our controller class.
@RequestMapper is used to map incoming HTTP request to handler method(welcome() in above
controller). So welcome() method of WelcomeController.java will handle GET request from
dispatcher.So when we call the url of "http://localhost:8080/welcome", then the welcome
method will get called.
Create property file: The next step is creating a application.properties file and putting it in
src/main/resoures.
Spring Boot provides rich set of Application Properties. So, we can use that in properties file of
our project. It helps to organize application properties.
Example:
# BANNER
banner.charset=UTF-8 // Banner file encoding.
# LOGGING
logging.config= // Location of the logging configuration file.
// For instance `classpath:logback.xml` for Logback
# AOP
spring.aop.auto=true // Add @EnableAspectJAutoProxy.
You can find a list of common Spring Boot properties and references at the following link:
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
6. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
Make your UI:
Use popular web technologies to build a Hosted Web App. By default Spring Boot serves static
contents like CSS or Javascript in the classpath at "/src/main/resources/static/" (or
"/src/main/resources/public").
The index.html resource is special because it is used as a "welcome page" if it exists, which means
it will be served up as the root resource.
Using JSP as view:
Default embedded servlet container for Spring Boot Starter Web is tomcat. To enable support
for JSP’s, you need to add a dependency on tomcat-embed-jasper.
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
Keep you JSP files in the " src/main/webapp/WEB-INF/jsp/" path.
Configuring a View Resolver:
To configure the view resolver add the following property files to application.properties:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
Remove Restarts:
Normally you’d have to restart your server each time you make a change to your front-end which
is a pain. Using Spring Boot’s developer tools allows us to get around this. Add the following
dependency to your POM.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
Also add this configuration to your Spring Boot Maven Plugin:
<configuration>
<addResources>true</addResources>
</configuration>
Now, when you make a change to your application, or recompile any classes, it should update
when you refresh your browser.
7. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
Running the Application:
Use the Spring Boot Application class (mail class tha you created before) to launch your
application. During running the application it produce the following output to the console.
If you look at the console log, you can find the following log message:
Started SpringBootExampleApplication in … seconds (JVM running for ….)
This message shows that the application is started. Now, we can send HTTP request from the any
browser to call the controller method.
8. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
Spring Boot Data:
The Spring Framework consists of a collection of projects, and one of these projects is Spring Data.
Spring Data provides extensive support for working with SQL databases, from direct JDBC access using
JdbcTemplate to complete JPA technologies. JPA is the Java Persistence API, which is Java's standard
API for object-relational mapping. JPA is only an specification, Hibernate is one of the most well-
known and most used implementations of JPA, but there are others, such as EclipseLink JPA.
Configuring DataSource in Spring:
In Spring Boot, dataSource configuration can be done in two ways:
using standard Spring Boot properties file
using Java @Configuration class
Using properties file:
To configure the data source using a properties file, we have to set properties prefixed with
spring.datasource. Spring Boot will automatically configure a data source based on those
properties:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/
TestDatabase?createDatabaseIfNotExist=true
sring.datasource.username=yourUserName
spring.datasource.password=yourPassword
Using Java Configuration class:
The Java configuration looks the same as it does in a standard Spring project:
@Configuration
@PropertySource(value = { "classpath:application.properties" })
public class DataSourceConfig {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(
env.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
return dataSource;
}
9. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
Configuring Connection Pool:
Spring Boot uses the following algorithm for choosing a specific implementation:
- Spring boot prefers HikariCP for its performance and concurrency. If HikariCP is available, it is
always a first choice.
- Otherwise, if the Tomcat pooling DataSource is available, spring uses it.
- If neither HikariCP nor the Tomcat pooling datasource are available and if Commons DBCP2 is
available, spring uses it.
If you use the spring-boot-starter-jdbc or spring-boot-starter-data-jpa “starters”, you
automatically get a dependency to HikariCP.
You can bypass that algorithm completely and specify the connection pool to use by setting the
spring.datasource.type property. This is especially important if you run your application in a Tomcat
container, as tomcat-jdbc is provided by default.
You can customize the connection pooling settings, by using their prefix:
for hikari: spring.datasource.hikari.*
for tomcat : spring.datasource.tomcat.* .
For example Tomcat connection pool will configure in application.properties as following:
# The initial number of connections that are created when the pool is started. Default is 10
spring.datasource.tomcat. initialSize=100
#The indication of whether objects will be validated when a connection is first created. If an
object fails to validate, it will be throw SQLException. Default value is false
spring.datasource.tomcat.testOnConnect=true
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.tomcat.max-wait=50000
# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=50
# Validate the connection before borrowing it from the pool.
spring.datasource.tomcat.test-on-borrow=true
# The maximum number of connections that should be kept in the pool at all times. Default value
is maxActive:100
# Idle connections are checked periodically (if enabled) and connections that been idle for
longer than minEvictableIdleTimeMillis will be released.
spring.datasource.tomcat.max-idle=15
# The minimum number of established connections that should be kept in the pool at all times.
The connection pool can shrink below this number if validation queries fail. Default value is
derived from initialSize:10
spring.datasource.tomcat.min-idle=10
Connection to a JNDI DataSource
10. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
If you deploy your Spring Boot application to an Application Server, you might want to configure and
manage your DataSource by using your Application Server’s built-in features and access it by using
JNDI.
The spring.datasource.jndi-name property can be used as an alternative to the (spring.datasource.url,
spring.datasource.username, and spring.datasource.password) properties to access the DataSource from a
specific JNDI location.
For example, you can access a JBoss AS defined DataSource as following:
spring.datasource.jndi-name=java:jboss/datasources/customers
Spring Data JDBC:
Spring Boot provides starter and libraries for connecting to our application with JDBC. Spring provides
JdbcTemplate class for database operations using JDBC. Spring JDBC dependencies can be resolved by
using the following dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Spring’s JdbcTemplate and NamedParameterJdbcTemplate classes are auto-configured, and you can
@Autowire them directly into your own beans, as shown in the following example:
@Repository
public class UserRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
public UserInfo getUserDetails(String userName) {
String sqlText = "select * from UserDetails where username = ?";
return jdbcTemplate.queryForObject(sqlText,
new Object[]{userName},
new BeanPropertyRowMapper<>(UserDetails.class));
}
}
We can autowire JdbcTemplate in the classes annotated with spring stereotypes such as @Component,
@Service, @Repository and @Controller. JdbcTemplate provides methods such as
queryForObject(), query(), update() etc to perform database operations.
11. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
Spring Data JPA:
Spring Data supports JPA via the Spring Data JPA subproject. Spring Data JPA aims to significantly
improve the implementation of data access layers by reducing the effort to the amount that’s actually
needed. The spring-boot-starter contains the necessary auto-configuration for Spring JPA:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
Devlopring Repositories in Spring Boot:
You can develop you repositories in spring data jpa in 2 way:
- Using Spring Data Repositories.
- Using an implementation of EntityManager.
Spring Data Repositories:
Spring Data JPA allows you to rapidly develop your data access layer through the use of Repository
interfaces instead of using EntityManager. The goal of Spring Data repository abstraction is to
significantly reduce the amount of boilerplate code required to implement data access layers for various
persistence stores.
The Spring Data core library ships with three interfaces that expose a dedicated set of functionalities:
- CrudRepository
- PagingAndSortingRepository
- JpaRepository
12. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
CrudRepository: provides methods for CRUD operations, so it allows you to create, read, update and
delete records without having to define your own methods. Spring provides CrudRepository
implementation class automatically at runtime. It contains methods such as save, findById, delete, count
etc.
Extending CrudRepository needs two parameters:
- The type of the entity that is managed by our repository.
- The type of the entity’s id field.
Custom Repository Methods: CrudRepository provides methods for generic CRUD operation
and if we want to add custom methods in our interface that has extended CrudRepository, we can
add in following ways:
a. We can start our query method names with find...By, read...By, query...By,
count...By, delete...By and etc.
- Before By we can add expression such as Distinct .
- After By we need to add property names of our entity.
Example: countByLastname, findTitlesByFirstName
b. To get data on the basis of more than one property we can concatenate property names
using And and Or while creating method names. Example:
countByLastnameAndFistName, findTitlesByFirstNameOrlastName
c. If we want to use completely custom name for our method, we can use @Query
annotation to write query.
13. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
Example:
interface UserRepository extends CrudRepository<User, Long> {
long countByLastName(String lastName);
long deleteByfirstName(String firstname);
// limiting the query result by FIRST
List<User> findFirst10ByLastName(String lastName);
// limiting the query result by TOP
List<User> findTop10ByLastName(String lastName);
List<User> findByEmailAddressOrPhoneNumber(String emailAddress,String phoneNumber);
// Enables the distinct flag for the query
List<User> findUsersDistinctByEmailAddressOrPhoneNumber(String emailAddress,
String phoneNumber);
// Enabling static IGNORE CASE for a query
List<User> findByLastNameIgnoreCase(String lastName);
// Enabling static ORDER BY for a query
List<User> findByLastNameOrderByFirstNameAsc(String lastName);
@Query("SELECT a FROM Users a WHERE a.firstName=:firstName AND a.lastName =:lastName")
List<User> fetchUsers(@Param("firstName") String firstName,
@Param("lastName") String lastName);
}
PagingAndSortingRepository:
On top of the CrudRepository there is a PagingAndSortingRepository abstraction that adds additional
methods to ease paginated access to entities. PagingAndSortingRepository provides options to
- Sort your data using Sort interface
- Paginate your data using Pageable interface, which provides methods for pagination:
getPageNumber(), getPageSize(), next(), previousOrFirst() etc.
14. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
JpaRepository:
provides some JPA related method such as flushing the persistence context and delete record in a batch.
Because of the inheritance mentioned in above picture, JpaRepository will have all the functions of
CrudRepository and PagingAndSortingRepository. So if you don't need the repository to have the
functions provided by JpaRepository and PagingAndSortingRepository , use CrudRepository.
@EnableJpaRepositories: This annotation will scan the package of the annotated configuration class for
Spring Data repositories by default. If your repository package is outside from the main application package,and
spring boot auto configuration couldn’t search it for some dependencies, then you should use this annotation to
declare the repository package:
@EnableJpaRepositories("com.soshiant.repository")
15. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
Using EntityManager:
Sometimes you will need to access the EntityManager from Spring Data JPA. The purpose of the
EntityManager is to interact with the persistence context. The persistence context will then manage
entity instances and their associated lifecycle. JPA architecture can be represented in the diagram below:
Entity : Entities are the persistence objects, stores as records in the database. you can designate any
POJO class as a JPA entity.
@Entity
@Table(name = "EMPLOYEE")
@NamedNativeQueries({
@NamedNativeQuery(name = "getAllEmployees",
query = "SELECT EmployeeId, FirstName, LastName,
EmailAddress,PhoneNumber,CreateDate FROM employee",
resultClass=Employee.class
),
@NamedNativeQuery(name = "getAllEmployeesByFirstName",
query = "SELECT EmployeeId, FirstName, LastName, EmailAddress,
PhoneNumber, CreateDate FROM employee WHERE FirstName=?",
resultClass = Employee.class
)})
public class Employee implements java.io.Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator =
"EmployeeSequence")
@SequenceGenerator(name = "EmployeeSequence", sequenceName = "employeeSeq",
initialValue = 1000, allocationSize = 1 )
@Column(name = "EmployeeId")
private Long employeeId;
private String firstName;
private String lastName;
private String emailAddress;
private String phoneNumber;
Date createDate;
public Employee() {}
}
16. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
The default constructor only exists for the sake of JPA. You won’t use it directly, so it is designated
as protected.
@Entity annotation defines that the class is an entity.
@EntityScan : If your enitities are not under the base package of application, you can customize entity
scanning locations by using the @EntityScan(“com.soshiant.entity”) annotation.
@Transient: The Transient annotation annotation is used to indicate that a field is not to be persisted in
the database and its values are never stored in the database.
@Table: This annotation allows you to specify the details of the table that will be used to persist the entity
in the database. If the table name and entity name are the same, you can omit @Table annotation.
@Id : The EmployeeId property is annotated with @Id so that JPA will recognize it as the object’s ID. The
@GeneratedValue: EmployeeId property is also annotated with @GeneratedValue to indicate that the
ID should be generated automatically.
@SequenceGenerator: This annotation defines a primary key generator that may be referenced by
name when a generator element is specified for the GeneratedValue annotation. A sequence generator
may be specified on the entity class or on the primary key field or property. The scope of
the generator name is global to the persistence unit (across all generator types).
@Column: The @Column annotation is used to specify the details of the column to which a field or property
will be mapped. If the property name and column name are the same, you can omit this annotation.You
can use column annotation with the following most commonly used attributes:
name attribute permits the name of the column to be explicitly specified.
length attribute permits the size of the column used to map a value particularly for a String value.
nullable attribute permits the column to be marked NOT NULL when the schema is generated.
unique attribute permits the column to be marked as containing only unique values.
@Temporal: This annotation is specified for Date and Calendar type persistent. It can have one of
following three values DATE, TIME, and TIMESTAMP. Default is TIMESTAMP.
@NamedNativeQuery: If you want to create a SQL query, you have to annotate your entity with the
@NamedNativeQuery annotation. If you want to create more than one named query, then you have to
wrap the queries inside the @NamedNativeQueries annotation.
@NamedQuery: If you want to create a JPQL query, you have to annotate your entity with the @NamedQuery
annotation. The name element of @NamedQuery specifies the name of the query that will be used with
the createNamedQuery method. The query element of @NamedQuery is the query. If you want to create
more than one named query, then you have to wrap the queries inside the @NamedQueries annotation.
17. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
Repository with EntityManger:
@Transactional
@Repository
public class EmployeeRepositoryImpl implements EmployeeRepository {
@PersistenceContext
private EntityManager em;
public Employee saveEmployee(Employee employee){
try{
em.persist(employee);
em.flush();
return employee;
}
catch (Exception e){
e.printStackTrace();
return null;
}
}
public List<Employee> getEmployeesByFirstName(String firstName){
return em.createNamedQuery("getAllEmployeesByFirstName",Employee.class).
setParameter(0, firstName).getResultList();
}
public List<Employee> getEmployeesByLastName(String lastName){
return em.createQuery("SELECT e FROM Employee e WHERE e.lastName ='" + lastName +
"'", Employee.class).getResultList();
}
}
Persist method: New entity objects can be stored in the database by invoking the persist method. An
explicit call to persist associates the object with an owner EntityManager em and changes its state to
Managed. The new entity object is stored in the database when the transaction is committed. JPA’s
persist is almost same as Hibernate’s save method. Both methods seem to do the same, but there are a
few differences. Notice that JPA’s persist method returns void but auto generated Id’s will be available
in the entity, after committing the transaction. Hibernate’s save method returns the primary key of the
entity.
Flush method: The EntityManager.flush() operation can be used the write all changes to the database
before the transaction is committed. By default JPA does not normally write changes to the database
until the transaction is committed. When you call persist, merge, or remove the database DML
INSERT, UPDATE, DELETE is not executed, until commit, or until a flush is triggered.
CreateQuery method: The createQuery method is used to create dynamic queries, which are queries
defined directly within an application’s business logic.
18. Hamid Ghorbani (Spring Boot) https://ir.linkedin.com/in/ghorbanihamid
CreateNamedQuery method: The createNamedQuery method is used to create static queries, or
queries that are defined in metadata by using the javax.persistence.NamedQuery annotation.
Named Parameters in Queries: Named parameters are query parameters that are prefixed with a colon (:).
Named parameters in a query are bound to an argument by the following method:
javax.persistence.Query.setParameter(String name, Object value)
In the following example, the name argument to the findWithName business method is bound to the
:custName named parameter in the query by calling Query.setParameter:
public List findWithName(String name) {
return em.createQuery(
"SELECT c FROM Customer c WHERE c.name LIKE :custName")
.setParameter("custName", name)
.getResultList();
}
Named parameters are case-sensitive and may be used by both dynamic and static queries.
Positional Parameters in Queries: You may use positional parameters instead of named parameters
in queries. Positional parameters are prefixed with a question mark (?) followed the numeric position
of the parameter in the query. The Query.setParameter(integer position, Object value) method is used
to set the parameter values.
In the following example, the findWithName business method is rewritten to use input parameters:
public List findWithName(String name) {
return em.createQuery(
“SELECT c FROM Customer c WHERE c.name LIKE ?1”)
.setParameter(1, name)
.getResultList();
}
The Related Example on Github:
https://github.com/ghorbanihamid/SpringBoot_AOP_JPA_Example