0% found this document useful (0 votes)
54 views5 pages

Spring Boot Fundamentals Overview

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views5 pages

Spring Boot Fundamentals Overview

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

----Spring Boot Fundamentals----

spring-boot-starter is already added in [Link] whenever we create a new Spring


Boot project

The main class should be like this

@SpringBootApplication //annotation marking the starting point


public class SpringbootdemoApplication {
public static void main(String[] args) {
[Link]([Link], args);
}

@SpringBootApplication -a collection of various annotations. The major 3 are as


follows
@EnableAutoConfiguration: enable Spring Boot's auto-configuration mechanism
@ComponentScan: enable @Component scan on the package where the application
is located (see the best practices)
@Configuration: allow to register extra beans in the context or impont
additional configuration classes

Note : we can change the default value of component scan.

** Spring Data JPA


All CRUD operations for Dao layers can be performed using extending JPA Repository.
- spring-boot-starter-data-jpa in [Link]

<dependency>
<artifactId>h2</artifactId>
</dependency>

fetches HSQL, DERBY which automatically creates the tables in the DB using
entities.

For MYSQL we need to add the following in [Link]:

-[Link]
-[Link]
-[Link]

Add [Link]-sql = true in [Link] to show what all queries


SpringBoot is using in the console.

Create an entity;
Then in Repository Layer
create a EntityRepository interface and extend JPARepository<EntityName, TypeOfId>

Now, it will automatically perform all the CRUD operations


For insertion -> [Link]();
There are different methods for CRUD already available in JPA.

** REST API and SQL:


Create new project
Add the following dependencies while creating.
-SQL, spring-boot-starter-web (for REST web services), jpa to be added while
creating project
Add @RestController() in the controller class.
@RequestMapping(method :)

-> To run Spring Boot project outside IDE


- Maven Install
- then run following command from command prompt
-java -jar target/productrestapi-0.0.1-snapshot. jar

By default - no context path is set for Spring Boot application.


However we can explicitly configure the path following the below steps
-Go to [Link]
-Add : [Link]-path=context-path-value-here

-> Change the embedded server in SpringBoot


- Go to [Link]
- Under the dependency of spring-boot-starter-web : add the following to
exlude the default Tomcat server
-<exclusions><exclusion><groupId>[Link]</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId></exclusion></exclusions>
- Then, add the following dependency according to requirements
-Eg: For Jetty .:
<dependency><groupId>[Link]</groupId> <artifactId>spring-boot-
starter-jetty</artifactId></dependency>

-> Making profiles for server


1) Test
2) Dev
3) Prod

Set the value of [Link] "devOrTestOrProdURL" in


[Link].

Steps :
- Duplicate [Link] twice and
- name [Link] and set value of
[Link]
- name [Link] and set value of
[Link]

Then set [Link]-dev/testing etc. according to the naming convention


of the [Link].
And then we can add a variable wherever we need to use
@Value("$[Link])")
private String baseURL;
User Logging:
Create a logger variable wherever needed (Here in @RestControllerFile)
privatť static final Logger LOGGER
LoggerFactory getLogger (AnyRestcontrollerClass. class);
[Link](); // Method to print out info/print messages
LOGGER. info()
There are other functions of Logger that we can leverage
Logging to a file
Go to [Link] > add "[Link]-logs/[Link]"
(logs/[Link] is the path of the file, we can set any path by providing
Logging Levels:
Add the following and more in [Link] according to the need
[Link]. root=error
[Link]=error
// This is tor root.
// This is fon springframework level.
What we are doing here is providing from where we need the logs and then providing
the levels/type of logs we need in the logs file created.

Health Checks and Metrics


**
Spring Boot provides the following for health metrics
Health Checks
Application Configuration
Application Metrics
Key Application Events
What are actuators ?
In essence, Actuator brings production-ready features to our application.
Monitoring our app, gathering metrics, and understanding traffic or the state of
our database becomes trivial with this dependency.
The main benefit of this library is that we can get production-grade tools without
actually having to implement these features ourselves.
The actuator mainly exposes operational information about the running application
health, metrics, info, dump, env, etc.
It uses HTTP endpoints or JMX beans to enable us to interact with it.
Once this dependency is on the classpath, several endpoints are available for us
out of the box.
As with most Spring modules, we can easily configure or extend it in many ways.
Add the dependency "spring-boot-starter-actuator" in [Link].
What happens is after adding this, when we hit the endpoint /actuator,
it exposes all the health related api endpoints, by clicking on it, we can see the
health and metrics of the application.
Expose health details
Go to [Link] -> [Link]-details-always (by
default, it is set to never I
phen-authorised is used for authorisation access)
Add build info in health metrics exposed
Add the following in [Link] under the dependency spring-boot-maven-plugin
<executions><execution><goals><goal>build-info</goalx</goals></executions></
executions>
Expose other endpoints
[Link]=* //Adding
means we are exposing every metrics endpoint here.

Create custom health information


Use @Component annotation.
Create any class and implement HealthIndicator interface.
create Health health()f if (some condition/ error) return
[Link]().withDetail().build(); else return [Link]().build();)
** Spring Security in Spring Boot
Add spring-boot-starter-security dependency in [Link]
the basic security check will be enabled.
..tbc.
Thymeleaf
In Spring MVC, for view, JSP files were used.
In SPring Boot, JSP files are replaced by Thymeleaf i.e. templating engine.
-Add spring-boot-starter-thymeleaf dependency in [Link]
A template folder is created where we can create html files for view.
How it works?
From the RestController API, return the thymeleaf template name or object. (See
video for reference)
Syntax
$fmodelname/element)
*(propertyName that would be binded with any message)
@urlt
Add [Link]=false in [Link] to refresh the web page
for any changes without restarting the server.

Database Caching
Caching data in memory so that ORM tools can look for records in cache for faster
response.
To enable caching, SpringBoot uses 3rd party cache providers like HazelCast,
RehitCast., JBossCast.
• When there are multiple servers, objects which are cached need to be serialized
by implementing the Serializable interface.
What is Serialization?
Serialization in Java is the concept of representing an object's state as a byte
stream.
The byte stream has all the information about the object. Usually used in
Hibernate, JMS, JPA, and EJB,
serialization in Java helps transport the code from one JVM to another and then de-
serialize it there.
Steps to enable caching :
spring boot-starter-cache and hazelcast (from groupId
Add dependency to pom.xm1 for SpringBoot and HazelCast
Com. hazelcast), hazelcast-spring
Provide config required for the cache. Give the name, size, # of objects that would
go into the cache. These would be in javaconfig class.
Create a config class
Add @Configuration
return a Config object by setting the name, ttl etc.
Enable and use caching - Use @EnableCaching annotation in RestController or Service
classes.
Enable caching in SPringBootApplication class using @EnableCaching
Make model class Serializable by implementing Serializable interface.
Then wherever(RestController or Service classes) for the required method,
add the annotations QCacheable("cache-config-name-set-in-cache-config-class")
//readOnly=true only for readOnly methods
and @transactional(readOnly=true)
@CacheEvict("cache-config-name-set-in-cache-config-class") for delete methods
Evict cache (when caches are cleaned) what policy to be used for handling cache
LRU, LFU, NONE, RANDOM
** Spring Batch

* * Messaging and Spring JMS


Messaging server/MOM (Message Oriented M..) is used to bridge between two
components of the application.
It helps in decoupling and allows communication between the components (can be
called microservices).
Messaging allows heterogeneous integration.
Loose coupling.
Web services are an alternative to messaging but messages maybe lost in web
services. MOM is more reliable as the messages are not lost andé
MOM persists the messages.
MOM allows for synchronous processing in case of long message queues and also,
it can use multiple consumers of the same component(microservices i.e. another
instance [Link] mircoservices)
Reduce system bottlenecks and traffic congestion. Thus, makes it scalable.
Flexibility and agility. Microservices can be easily replaced and used.
2 types of messages
1) Point to point
2) Publish/subscribe

Common questions

Powered by AI

A Message-Oriented Middleware (MOM) is more beneficial than traditional web services in scenarios that require reliable communication without data loss. Unlike web services, MOM persists messages, ensuring they are not lost during transmission even with long message queues. It supports asynchronous processing and better scalability by reducing system bottlenecks and traffic congestion. In Spring JMS, MOM facilitates loose coupling and heterogeneous integration, making it suitable for microservices that require flexibility and resilience .

Setting up user logging in a Spring Boot application involves creating a static final Logger instance through SLF4J's LoggerFactory within a class, typically a RestController. Methods like LOGGER.info() can then print informative messages to the console or log files. Adding logging.file-logs/application.log in application.properties facilitates saving logs to a file. This setup allows for effective monitoring and debugging, helping developers trace application logic and runtime behavior quickly .

Spring Data JPA facilitates CRUD operations by allowing developers to extend the JPARepository interface, which provides methods for these operations (e.g., save, findAll, etc.). To integrate with a MySQL database, the following configurations should be added to the application.properties file: spring.datasource.url, spring.datasource.username, and spring.datasource.password. Additionally, setting spring.jpa.show-sql to true will display the queries executed by Spring Boot in the console .

Serialization in Java is crucial when enabling caching with multiple servers in a Spring Boot application. It represents an object's state as a byte stream, facilitating the transportation of cached objects across different JVMs. This process ensures the integrity and consistency of object data when it's retrieved from the cache, enabling dynamic scaling and distribution of application architecture across multiple nodes without breaking data synchronization .

Application profiles in Spring Boot can be configured by creating separate application-{profile}.properties files for 'dev', 'test', and 'prod' environments. Specific configurations relevant to each environment are set within these files, such as different database URLs or API endpoints. Profiles can be activated by setting spring-profiles.active in application.properties. This approach offers flexibility in managing different configurations, enabling developers to easily switch between environments and maintain environment-specific settings without code changes .

The @SpringBootApplication annotation in Spring Boot is a composed annotation that includes several key components: @EnableAutoConfiguration, @ComponentScan, and @Configuration. @EnableAutoConfiguration enables Spring Boot's auto-configuration mechanism, which attempts to configure the application based on the dependencies present on the classpath. @ComponentScan enables the scanning of components (e.g., @Component, @Service) in the specified package where the application is located. @Configuration allows us to register additional beans or import extra configuration classes .

To expose health and metrics endpoints using Spring Boot Actuator, the dependency "spring-boot-starter-actuator" must be added to the pom.xml file. Once added, these endpoints can be configured using application.properties, such as setting management.endpoint.health.show-details-always to expose health details. The endpoints provide operational information about the application, allowing for monitoring of app status, gathering metrics, and understanding database states .

The @EnableCaching annotation in Spring Boot enables the caching infrastructure, allowing the application to interact with various cache providers such as Hazelcast. By adding this annotation, Spring Boot can recognize and execute caching logic annotated with @Cacheable or @CacheEvict. For integration with Hazelcast, the necessary configuration can be defined in a Java configuration class, including cache name, size, and other parameters required to manage cache instances .

To change the embedded server in Spring Boot from Tomcat to Jetty, the spring-boot-starter-web dependency in the pom.xml should exclude the Tomcat starter using an exclusion block. Then, the spring-boot-starter-jetty dependency needs to be added. The implications of using Jetty over Tomcat include differences in performance characteristics, memory usage, and possibly configurations specific to each server. Jetty may offer better support for certain asynchronous processing tasks due to different optimizations .

Thymeleaf enhances separation of concerns by serving as a templating engine that allows developers to maintain clear distinctions between business logic and presentation. To utilize Thymeleaf in Spring Boot, the spring-boot-starter-thymeleaf dependency needs to be included in the pom.xml. To refresh web pages without restarting the server, the configuration spring.thymeleaf.cache should be set to false in the application.properties file, enabling immediate template updates to be reflected in the web view .

You might also like