LIVE NOTES
LIVE NOTES
Spring and spring framework for web app development
Container & Spring Bean management.
To make a Spring Bean majorly used annotations
Experiment, when dependency bean is not in container and you are asking for it. Spring fails
Dont create cyclic dependency in your beans - spring fails
Coding with Spring & Spring Boot
=====================
wp - 9-10hrs
1. Week3 (Mon)
Mon-Fri morning 8:30AM - Daily Standup Meeting
15-20 mins
20Oct daily 8:30
10AM
...
...
6 - 6:30
7:00 - 10.5
7:30PM - 11hrs
=======
2. Every Friday for 1hr, reserve for summary.
10-12 -
12 PM - 1PM
revision topic. which will be given by 2 of you guys.
Week2 now
- Week2 complete - 1demo
- Google form: I AM INTERESTED
- Attendance & Tasks. 70%
W3D5 (Fri)
Tueday - finalize 2members
TUE-WED-THU - FRI
12 PM - 1PM
2 members are supposed to summarize the last week (Week2)
30mins slot
Spring & Spring Boot
Spring has multiple projects & modules.
For building different types of projects, you would use different "projects & modules" given by
spring.
Spring Core Framework
needed on daily basis in coding. Even for spring boot application.
IOC - Inversion of Control
The object creation & maintenance is Developer responsibility
MyClass obj = new MyClass();
obj.met2();
close
Gargage
Memory leak.. memory pipe up.. application getting stuck.
creat object.
excep
no proper handling..
IO
IOC
Inversion of Control
Framework creates & manages objects for you.
Developer does not do it.
Control is inverted. taken away from developer
How is IOC implemented in spring.
Container
spring uses container to create & manage objects.
objects which are crated & managed by container are called as spring beans.
2 types of container
- Bean factory container
- Application Context Container.
is extension of bean factory with more features & capabilities.
When you create an object using "new", then spring is not managing it you are managing..
but when spring manages then spring does a lot of things..
Week1 code.
AdditionController is provided with values of
@Value("${[Link]}")
private String myKey;
@PostConstruct
private void init() {
[Link]("====>Value read from property myKey:{}", myKey);
}
When you manage the objects, mean you create & work with it.. then spring will not be value to
do object management..
@Value will not work, @PostContruct..
spring is not in control of this object.. so it doesn't do anything.
How to make spring to take control of this AddService object.
Annotations for doing this.
@Override
when you use annotation, some jar file is having code for that annotation.
this code will give special behaviour..
The primary annotation for putting object in control of spring
@Component
@Component
public class AddService {}
AddService addService = new AddService();
int sum = [Link](request);
for all important classes of your project. you let the spring create & manage objects.. you are not
supposed to do it..
Spring Beans
when spring is creating & managing objects.
how is AdditionController part of the container?
spring framework provides core annotations to use, which will make objects as spring bean
(created & managed by spring)
Directly or indirectlty it should extend @Component
Which annotations to make spring bean
===================
@Component
@Service - core business logic
@Repository - database
@Controller - Spring MVC
@RestController - RestAPIs
@ControllerAdvice - Exception handling spring mvc
@RestControllerAdvice - Exception handling Rest API
@Configuration - used to create new spring beans..
===================
Annotations can be applied at different places.
dependending on your requirements you can use above annotations, to make your java class
oject as a spring bean.
Incase you are not able to categorize the object, then simply use @Component annotation.
When controller wants to call service
--------------------------------------
You are not supposed to create a new service class object using "new"
Instead ask the spring container to give you the service object reference, which is managed by
spring.
once spring gives the you object reference then you can call the destination method.
===================
How can 1 spring bean, wants to have access to another spring bean
- from container ask & call. (how to do this technical)
=> Dependency Injection
=> Dependency lookup
Dependency Injection
@Autowired
===
@Service on our bean
@Autowired - for giving the reference.
comment @Service???
will it work
will it not work?
- service startup problem
- execution time problem
1. It will work successful
2. It will fail on service startup
3. It will fail on execution time
@Service & //@Autowired
@Service & @Autowired
works
//@Service &
@Autowired
service object was not in container, & you were asking it, so spring is confusions and
startup failed.
spring boot startup failed
@Service & //@Autowired
object is there in memory, and you have not asked for it..
so spring doesnot have problem, service starts.
when you run it.. spring will not give it to you directly.. so the value will be null.
that results in null pointer
=> 3. It will fail on execution time
1. It will work successful
2. It will fail on service startup
3. It will fail on execution time
================= Circular referencing
in controller
@Autowired
private AddService addService;
Service
@Autowired
private AdditionController additionController;
avoid circulrar dependency.
spring will fail by default.. not allowing circular referencing
=======================
1 bean wants to have reference of another bean.
=> Dependency Injection
=> Dependency Lookup
Dependency Injection
@Autowired
There are different types of dependency inject.
field injection
the dependent bean is injected on your field.
when we used @Autowired on field,
constructor injection
the dependent bean is injected through your constructor.
when we used @Autowired on contructor,
setter
method
when controller object is being created, give me object of service via field.
field injection
when controller object is being created, give me object of service via constructor.
constructor injection
Sonar says use constructor injection.
How to write constructor injection.
---------------------
AddController {
AddController(AddService serviceObj){
}
====================
private AddService addService;
@Autowired
public AdditionController(AddService addService) {
[Link]("====> CONTROLLER Constructor addService:{}", addService);
}
===================
while doing constructor injection ensure, the value is assigned to your instance field.
private AddService addService;
@Autowired
public AdditionController(AddService addService) {
[Link]("====> CONTROLLER Constructor addService:{}", addService);
[Link] = addService;
}
========
=====================
When doing constructor injection, @Autowired on controller is optional.
also make sure, you dont apply both constructor & field injection.
private AddService addService;
public AdditionController(AddService addService) {
[Link]("====> CONTROLLER Constructor addService:{}", addService);
[Link] = addService;
}
=====================
lombok
@RequiredArgsConstructor
creates contructor. required args
@RequiredArgsConstructor
public class AdditionController {
@Value("${[Link]}")
private String myKey;
private final AddService addService;
}
============================
AI SUMMARY
Summary
Tausief S. introduced "Coding with Spring and Spring Boot," covering core
concepts like Inversion of Control (IOC), Spring Beans, and various
annotations such as `@Component`, `@Service`, and `@Autowired`. Tausief
S. also elaborated on dependency injection styles, strongly recommending
constructor injection over field injection for better performance and best
practices, and provided practical demonstrations on implementing it with
and without Lombok. Finally, Tausief S. announced upcoming optional daily
standup meetings and weekly summary presentations, emphasizing the
importance of a professional work schedule, logical thinking, and digital
hygiene to combat distractions and foster focus for personal and
professional growth.
Details
● Introduction to Spring and Spring Boot Tausief S. introduced the day's topic,
"Coding with Spring and Spring Boot," emphasizing its importance for both
beginners and confident users (00:00:00). They conducted a poll to gauge the
audience's confidence levels with Spring and Spring Boot basics, noting that
while 13 members were confident, a larger section still needed foundational
knowledge (00:01:48). Tausief S. also stated that the session would focus on
changing the audience's perspective on the framework, moving beyond just using
it to understanding its underlying behavior for effective debugging (00:03:42).
● Upcoming Daily Standup Meetings Tausief S. announced that starting Monday of
week three, an optional daily standup meeting would be held from 8:30 a.m. to
8:50 a.m. This 20-minute meeting is designed for planning and reviewing work
progress, similar to corporate practices, and will run throughout the entire two-
month batch (00:04:56). They also stressed the importance of adopting a
professional work schedule, encouraging participants to dedicate 9-10 hours
daily to tasks and job hunting, and to avoid distractions during these hours
(00:06:00).
● Weekly Summary Presentations Tausief S. introduced a new initiative where
every Friday, from 12:00 p.m. to 1:00 p.m., two participants would summarize the
previous week's topics (00:08:42). Each participant would get a 30-minute slot to
explain the concepts, collaborating with their partner (00:11:07). Selection for
these presentations would be based on criteria such as submitting the weekly
demo, expressing interest via a Google form, and maintaining at least 70%
attendance and task completion (00:12:04).
● Evolution of Web Application Development in Java Tausief S. explained the
progression of web application development in Java, starting from core Java and
evolving through servlets and JSPs, which provided the foundational
technologies for web applications (00:16:35). They highlighted that frameworks
like Spring were built on top of these core technologies to reduce additional
coding and maintenance effort (00:18:01). Spring, being a vast framework with
various modules, further extended its capabilities with Spring Boot, aiming for
rapid application development (00:19:23).
● The Relationship Between Spring and Spring Boot Tausief S. clarified that Spring
Boot is an extension of the core Spring framework and not a replacement
(00:22:09). They addressed a common misconception among students,
emphasizing that learning core Spring is essential and cannot be skipped, as
Spring Boot internally relies on it (00:23:30). Tausief S. stressed that
understanding core Spring concepts and their practical application is crucial for
day-to-day coding in Spring Boot applications (00:25:38).
● Inversion of Control (IOC) as Spring's Core Power Tausief S. identified Inversion
of Control (IOC) as the fundamental concept at the heart of the Spring
framework, around which everything else revolves (00:26:42). They explained
that IOC means the control of object creation and management is taken away
from the developer and given to the framework (00:27:51) (00:31:46). This
inversion addresses past issues like memory leaks and application crashes
caused by improper object management by developers (00:29:16).
● Implementing IOC with Spring Container and @Component Annotation Tausief
S. detailed how IOC is implemented in Spring through a "container," also known
as an IOC container or Spring container, which is responsible for creating and
managing objects (00:34:38). They demonstrated that when developers create
objects using the `new` operator, Spring does not manage them, leading to
issues like `@Value` annotations and `@PostConstruct` methods not working as
expected (00:36:13) (00:46:38). To enable Spring to manage an object, Tausief S.
introduced the `@Component` annotation, explaining that placing this annotation
on a class tells Spring to take control of its object lifecycle, including initialization
and dependency injection (00:50:46). They illustrated this by showing how
`@Component` enabled the service's constructor and init methods to be called by
Spring, leading to proper object management (00:53:59).
● Managing Objects with Spring Tausief S explained that developers should allow
Spring to manage core important classes and their objects, rather than creating
them manually, to avoid project issues (00:59:40). When Spring creates and
manages objects, they are referred to as "spring beans" (01:00:55).
● Spring Bean Annotations Tausief S detailed how various annotations make
objects into spring beans. He clarified that `@Component` is the primary
annotation, and others like `@RestController`, `@Controller`, `@Service`,
`@Repository`, `@Configuration`, `@ControllerAdvice`, and
`@RestControllerAdvice` extend its behavior, directly or indirectly enabling Spring
to manage the object (01:02:21). Each annotation serves a different purpose,
with `@Service` for business logic and `@Repository` for database interactions
(01:12:26). If a class cannot be categorized, `@Component` serves as a generic
placeholder (01:15:00).
● Annotation Application and Behavior Tausief S described that annotations can
be applied at different levels, such as class, method, constructor, or variable, with
their target defined by the creator (01:09:50). Each annotation provides a special
behavior, for instance, `@Value` reads from a property file, and `@PostConstruct`
runs a method after object creation (01:11:12).
● Dependency Injection vs. Dependency Lookup Tausief S introduced two
approaches for one Spring bean to access another: dependency injection and
dependency lookup (01:19:59). He emphasized that controllers should obtain
service objects from the Spring container rather than creating new instances,
which would lead to unmanaged objects outside the container (01:16:35).
● Autowiring Objects Tausief S demonstrated how the `@Autowired` annotation
enables Spring to inject object references. When `@Autowired` is used on a field,
Spring searches its container for an object of that type and assigns it, ensuring
successful method calls (01:23:49).
● Impact of Missing `@Service` Annotation Tausief S conducted an experiment
where commenting out the `@Service` annotation on a class, while keeping
`@Autowired`, caused the Spring application to fail at startup (01:29:50)
(01:35:18). This occurs because the developer is asking Spring for an object that
was not instructed to be managed within the container, leading to confusion and
a startup failure (01:36:34).
● Impact of Missing `@Autowired` Annotation Tausief S presented another
experiment where the `@Service` annotation was present, but `@Autowired` was
commented out (01:39:28). In this scenario, the service starts successfully
because Spring manages the object, but without `@Autowired`, the object
reference is not automatically assigned, resulting in a NullPointerException at
runtime when a method is called (01:44:31) (01:51:44).
● Cyclic Dependency Issues Tausief S explained that creating a cyclic dependency,
where a controller `@Autowired` a service and the service `@Autowired` the
controller, causes the application to fail during startup (01:53:48). Spring detects
this circular reference and prohibits it by default, as it creates a deadlock in
object creation (01:57:08).
● Circular Dependency Tausief S explained that circular dependencies, where two
or more beans are interdependent in a cycle, can cause issues with Spring's
initialization and lead to unexpected application problems. They emphasized that
while Spring provides an option to allow circular referencing as a last resort, it is
strongly recommended to avoid designing systems with such dependencies to
ensure proper framework behavior and stability (01:59:26) (02:01:56).
● SonarQube Best Practices Tausief S highlighted SonarQube's role in identifying
coding best practices, particularly the suggestion to remove unused code and to
favor constructor injection over field injection. They advised developers to pay
attention to SonarQube's recommendations, noting that some projects might
mandate resolving higher severity issues (02:04:05).
● Dependency Injection Styles Tausief S elaborated on dependency injection,
explaining that `autowired` is a dependency injection style with different types,
including field injection and constructor injection. They defined field injection as
injecting a dependent bean directly onto a field and constructor injection as
injecting it through the constructor (02:06:55).
● Constructor vs. Field Injection Tausief S stated that SonarQube and general best
practices recommend using constructor injection due to its faster and more
optimized performance. They demonstrated that in constructor injection, the
dependent class is provided when the object is created, which is more efficient
than field injection where the object is first created and then fields are initialized
(02:08:33) (02:33:40).
● Implementing Constructor Injection Tausief S demonstrated how to implement
constructor injection by writing a parameterized constructor that accepts the
dependent service object (02:12:44). They emphasized the crucial step of
assigning the injected object to an instance field within the constructor to
prevent null pointer exceptions (02:18:28) (02:22:00).
● Optional `@Autowired` for Constructor Injection Tausief S explained that the
`@Autowired` annotation is optional for constructor injection because Spring is
intelligent enough to provide the reference to the parameterized constructor even
without it (02:36:11). They cautioned against using both field and constructor
injection simultaneously, as it can cause confusion despite Spring's internal
optimization (02:38:33).
● Lombok for Constructor Injection Tausief S introduced Lombok's
`@RequiredArgsConstructor` annotation as a way to automatically generate
constructors for required (final) arguments, thereby eliminating the need for
manual constructor writing and reducing the risk of errors (02:44:12). They noted
that Lombok simplifies the code and handles the assignment of injected
dependencies automatically (02:45:28).
● Importance of Logical Thinking and Digital Hygiene Tausief S discussed the
importance of logical thinking, problem-solving, and utilizing AI effectively for
self-learning (02:46:38). They also shared personal strategies for digital hygiene,
such as curating social media feeds and consuming only valuable information, to
protect one's brain from negative influences and maintain focus on personal
goals (02:50:31).
● Smarter Constructor Injection Tausief S. discussed a more intelligent approach
to constructor injection, emphasizing that it eliminates the need to explicitly write
constructors or use `@Autowired` (02:59:09). They suggested using a final
variable instead.
● Importance of Focus Tausief S. shared insights from Brand Tracy, highlighting
focus as the most significant factor for success in life (03:00:12). They
expressed concern about "attraction to distraction," which they believe
guarantees failure due to shortened attention spans, laziness, and context-
switching. They noted that distracted individuals have little chance against
focused ones, as focus trains the mind (03:01:22).
● Combating Distraction Tausief S. explained that a significant portion of many
people's day, approximately 80%, is spent distracted, leading to exhaustion and
an inability to perform meaningful tasks. They shared that they personally
stopped spending excessive time on social media in January 2024 to combat
this, as it made their mind tired (03:02:48). They encouraged attendees to control
their social media consumption and prioritize time for areas of success,
asserting that changing one's habits is possible (03:04:56).