Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
32 views

Spring Boot Fundamentals Udemy Notes

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Spring Boot Fundamentals Udemy Notes

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

----Spring Boot Fundamentals----

spring-boot-starter is already added in pom.xml 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) {
SpringApplication.run(SpringbootdemoApplication.class, 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 pom.xml

<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 application.properties:

-spring.datasource.url
-spring.datasource.username
-spring.datasource.password

Add spring-jpa.show-sql = true in application.properties 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 -> entityRepositorylbject.save();
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 application.properties
-Add : server.servlet.context-path=context-path-value-here

-> Change the embedded server in SpringBoot


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

-> Making profiles for server


1) Test
2) Dev
3) Prod

Set the value of productrestapi.services.url "devOrTestOrProdURL" in


application.properties.

Steps :
- Duplicate application.properties twice and
- name application-dev.properties and set value of
productrestapi.services.url
- name application-dev-testing.properties and set value of
productrestapi.services.url

Then set spring-profiles.active-dev/testing etc. according to the naming convention


of the application.properties.
And then we can add a variable wherever we need to use
@Value("$fproductrestapi.services.url)")
private String baseURL;
User Logging:
Create a logger variable wherever needed (Here in @RestControllerFile)
privatť static final Logger LOGGER
LoggerFactory getLogger (AnyRestcontrollerClass. class);
LOGGER.info(); // 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 application.properties > add "logging.file-logs/application.log"
(logs/application.log is the path of the file, we can set any path by providing
Logging Levels:
Add the following and more in application.properties according to the need
logging.level. root=error
logging.level.org.org.springframework=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 pom.xml.
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 application.properties -> management.endpoint.health.show-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 pom.xml under the dependency spring-boot-maven-plugin
<executions><execution><goals><goal>build-info</goalx</goals></executions></
executions>
Expose other endpoints
management.endpoints.web.exposure.include=* //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
Health.down().withDetail().build(); else return Health.up().build();)
** Spring Security in Spring Boot
Add spring-boot-starter-security dependency in pom.xml
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 pom.xml
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 spring.thymeleaf.cache=false in application.propertieg 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 of.the 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

You might also like