Sunteți pe pagina 1din 41

9401159929931509

-----------------------------------------------------------------------------------
-------------------
Date: 15/10/2019
-----------------
1.What is Spring Framework?
= Spring is a framework which is used to build application sofastictaedly.
Spring framework work over the language layer.
And language layer is communicate with hardware/OS to perform operations.
Suppose there are api's in language layer which is having 300 classes then by
using spring frmaework
over that language layer we have only 150 classes to work with.
So spring provides the ease of coding and faster application devlopment with
lot's of benefits.

2.By using Spring framework we can devlop any kind of application:


=1.Integration tier Application
2.Standalone application
3.Distributed Application
4.Enterprise Application
5.Database tier Application
6.GUI Application etc..

-By using STURTS Framework we can only devlop WEB-Application


Because STRUTS Provides abstraction only over Servlet and Jsp Technology(i.e.
Api's)

-----------------------------------------------------------------------------------
-------------------
Date: 16/10/2019
-----------------
3.What is Struts?
= Sturts is a most successful framework and mostly adopted by 100% people in
industry.
However, struts f/w provided only building application of Web type that means it
provided Api's only
for Servlet and JSP so Struts is not used for end to end devlopment of an
application.
In web type application or any type of application there are sevral areas like,
UI tech, Persistance
Logic, Business logic, Servlet, JSP and many for processing the request and to
providing the Response.
But Struts f/w provided API's over the servlet and JSP to build the web
application and for other
things we still need to depend over other than Sturts f/w classes or API's, that is
why Struts is not
used or not useful in end to end Application Devlopment.
Struts provided Action class to replace Servlet Api and because of this the
simplicity of devloping
Application is get used widely.

= Different types of Application use Different api's for devlopment:

---API's are made up of Different classes which are Interfaces and Abstract Classes
that means they are
partially implemented so Framework's will further implement them and provide us the
new API's to work
with and because of that the simplicty will get achived to build the application.
1.Standalone application(jdk)
2.GUI Based application(jdk)
3.Database tier Application(jdbc)
4.Integration tier Application(jax)
5.Enterprise Application(jee)
6.Distributed application(jee)

-----------------------------------------------------------------------------------
-------------------
Date: 17/10/2019
-----------------

= Struts is a framework by which we are devloping web application but not the end
to end application
when any request comes then either html,jsp or servlet will get called by that
request and the response
goes to user/client. So here client can directly communicate by UI technology to
servlet,jsp or html
So Struts supports Presentation layer component (Servlet,JSP,HTML)

=Java language can provide us a Single Api in which every thing will get included
however they won't
did the same because suppose if we want to release a new thing or class with
respect to servlet class
then we should release a complete Api again this will be more heavy and not
efficient as well, so they
made different Api's for different purpose and technology so ease of use and
simplicity will get
followed.
Api's contains more number of classes which will be abstract classes, interfaces
and so on. So to work
with any Api we need more ammount of time so suppose if client comes to us with
project requirement and
devloper
need to work with any new Api so first he need to learn that Api and the best
Implementation classes of
it, to find this effiecient way the deadline will end and if we took more number of
devlopers to do this
then also the cost will get increased so Api's are difficult to learn and also one
won't know to use
which classes and it's respective methods.
Api classes are interconnected to each other like there will be interface and one
abstract class will
implement that interface again another class will extends that abstract class and
then we need to use
that class and it's methods so Api classes are interconnected with each other.
Api classes and their implementation are present in different impl classes

=So frameworks are came into the picture to avoid such complexity and it's time
consuming to work with
Api's Framework will provided such interfaces and classes which are built on the
top of language and
technolgy Api's and they simplified it's implementaion though, so we just have to
use them as per our
need.

=Suppose we have to write an JDBC code to execute and select query if we want to
again execute different
query again we have to repeat all the code and steps so that repeated code is
called boiler plate code.
Api's only provided inetrfaces and abstract class further we need to implement them
and extend them
and then programmer need to write that code and for same task also we need to
repeate the code as per
the interface specification so that code repeated and tends to boiler plate code.

Api not provides boiler plate code, programmer has to write boiler plate code
JDBC not provided the SqlStatement class in which all is with ResultSet
execute(String sql){}
method and we just need to call execute method and pass the query and it will
return us the ResultSet,
instead of that we need to write same code again and again but with the help of
framework we can do this.

-----------------------------------------------------------------------------------
-------------------
Date: 18/10/2019
-----------------

=Why Not api why Framework?


With api we have to know and have to study the best implementaion classes and Api's
will not provide
the boiler plate code,
Unlike Api framework are devloped in such way that they will provide us the classes
with boiler plate
code, we just need to create the object of class and we have to call the method
There are sevral benifits while going with framework:
-the framework devloper will use the best practices and provide code optimization
for code they are
providing in framework classes, where as in api we have to write the code
optimiztaion and it will
end up with time consuming process
-as the code is optimized and already tested the chances of having bugs are less
where as in Api the
code is not optimized and we have to write lot of lines of code and the chances of
having more bugs
is high.
-as the code is optimized we need less number of testers where as in api we are
devloping the appln
we need more number of testers
-also we need less time and less devlopers
-the rapid application devlopment will get achived by this.

-----------------------------------------------------------------------------------
-------------------
Date: 19/10/2019
-----------------

-----------------------------------------------------------------------------------
-------------------
Date: 20/10/2019
-----------------

-----------------------------------------------------------------------------------
-------------------
Date: 21/10/2019
-----------------
-Why Spring is Light weight
= Because it is divided into modules
-Every module is independent they are not like api's

-Is that Spring framework is replacement of JavaEE JEE?


=No because it is built over the JEE Api
-Core module is base module for each module and all modules are dependent over core
Module

|------------------------------------------------------------------------|
| Spring Boot |
|------------------------------------------------------------------------|

|------------------------------------------------------------------------|
| Spring MVC/Flux |
|------------------------------------------------------------------------|

|-----| |-----|
|aop | |jdbc |................................
|-----| |-----|

|------------------------------------------------------------------------|
| Core module |
|------------------------------------------------------------------------|

-----------------------------------------------------------------------------------
-------------------
Date: 31/10/2019
-----------------
-What Challanges Spring have to compite with Already available Struts Framework in
Market?
=
1.As sturts is already been used in software devlopment from long time so to switch
with new framework
is quite challanging for devlopers and thus many of the application is already in
production and running
phase so everyone can not switch to new framework.

2.As Sturts having latest release of Sturts 1.4 when Spring is arrived then the
Sturts already in stable
position as they overcome the bugs and optimized it in latest release, where as
Spring is new bee and
devloper are not aware about it so if bug occurs in f/w so they have to wait until
next stable release.

3.Sturts and Spring are both open sourcs framework so there is uncertanity of it as
well, if anyone uses
Spring and if it is gone then we can't go anywhere or can't blame anyone about it.

4. As sturts is already been used by lot of people in market it became a next door
boy for devlopers to
work with if any problem arise our next collegue in our team will help for the
problem.

5.As spring is there from long time in market there are may peoples who are
habitual of only using
sturts for devlopment so everyone who is more experienced they are recommending
Sturts.

6.Stutrs also have rich documentation and large community with it which make stutrs
more market
demanding to use.

-----------------------------------------------------------------------------------
-------------------
Date: 01/11/2019
-----------------
--Features of Spring:-
-Dependancy management
-Versatile (Story of versatile)
-Non-Invasive
-End to end devlopment
-Cloud support
-microservices.....etc.

-----------------------------------------------------------------------------------
-------------------
Date: 02/11/2019
-----------------
-Cloud:-
-Iaas: Providing hardware resources only as per the requirement.
-Saas: Providing required set of softwares preinstalled on hardware requirement as
per the need.
-Paas: Providing both hardware and software resources as per the demand.

Microservices:
-Previously vertical scalling, i.e.we have to write entire application and need to
deploy on another
machine when request limit increases. Using microservices we can make horizontal
scalling like the
component which have more number of requests only that will expanded.
And to keep track on which system which module is running Spring microservices will
help.

-----------------------------------------------------------------------------------
-------------------
Date: 04/11/2019
-----------------
***SPRING CORE MODULE***:::------Dependancy Management.
________________________

-Modularity:
-We won't write complete code in one single class so as per the type and nature of
the code we use
different classes.
So when we need a piece of code again the we are not going to write it again and
again instead of that
we write that code as a Class or Method so we can use it again.
Hence, modularity is nothing but writing the classes or code as per its nature and
like module and due
to this reusability and redability will get increased.

-Isolation:
When we have a class and to run that code we are not dependent on any other class
then that class is
said to isolated or independent. Viceversa it will called as Non-Isolated.

-The classes are specified as per their nature.

-Types of classes in Application Devlopment:


1.POJO (Plain Old Java Object):
-The class which does not use any third party liabraries in it's classpath to
compile and run is known
as POJO Class.

2.Java Bean:
-The Class which contains Attributes with Default constructor as public, and has
Accessor methods
(i.e. Setters & Getters) is known as Java Bean class

3.Bean/Components:
-The classes which contains Arbitary type of methods which includes business logics
is known as Bean
class or components.

-----------------------------------------------------------------------------------
-------------------
Date: 05/11/2019
-----------------
-What is Spring Core?
-Object Management/Dependancy management.

-Dependancy between Classes?


-When one class can't complete its execution and it will need other class logic
inside it, then that class
is said to Dependent class.

-Can Spring Core provide Dependency/Object management for all types of Classes?
-Yes, by using Spring Core we can make any no. of arbitary(we can write any type of
logic in it) classes
dependent on each other without following any type of rules.
BUT, if programmer want more advantages then he has to follow certain set of rules
by which more benifits
can achived.

-So that to get that more benefits we have to implement Statergy Design Pattern in
Spring Core.

-What is Design Pattern?


-The Design patterns contains Standardise set of solutions which has been provided
by Experts for
recurring(common) problems.
e.g. Traffic Soultion's
-It was Introduced by GOF (Gang of Four people's) and it named as GOF DP.

-Statergy Design Patterns:


-It consist of 3 rules i.e.:
1.Favour composition over Inheritance
2.Use Interfaces but not Concrete classes.
3.Open for Extension, closed for modification
-----------------------------------------------------------------------------------
-------------------
Date: 06/11/2019
-----------------
1.Favour Composition over Inheritance.
-Both Composition And Inheritance provide the feature of reusability. However we
will see the both in
deep.

-Inheritance:
-Getting all the functionlaitis(methods,etc..) to our class by extending our
classby another is known
as Inheritance.
-It makes the IS-A relationship between classes.
e.g. class B{
public void m2(){
//logic
}
} class Test{
class A extends B{ psv main(String[] args){
public void m1(){ A a = new A();
m2(); a.m1();
} }
} }
-Composition:
-Creating attribute of another class in our class and creating object of that class
and calling that
class methods is known as Composition.
-It makes HAS-A relationship.
e,g, class B{
public int m2(){
return 30;
}
}
class A(){
B b;
public void m1(){
b = new B();
int x = b.m2();
}
}

-----------------------------------------------------------------------------------
-------------------
Date: 07/11/2019
-----------------

Why Composition, over Inheritance?


When we go for Inheritance and when to go for Composition?
-When we make inheritance between classes then all the functionality comes to our
classes, but also
our class will be said to be same as that class though, Inheritance means having
all the functinons as
it is and class will become same, so it will be said to be EXTENSION of class.
-Suppose, A computer has a printer to take the printouts when we need the
functionalities of printer we
can not say that our computer is a printer.
e.g. class Transmitter{
public void frequency(int hrtz){}
public void tune(double power){}
public void control(String status){}
}
class Radio{
public boolean on(){}
public boolean off(){}
}
Case 1:
-let's say Radio need the frequency to tune the channel so, if we go for
Inheritance
class Transmitter{
public void frequency(double hrtz){}
public void tune(double power){}
public void control(String status){}
}
class Radio extends Transmitter{
public boolean on(){
frequency(93.5);
}
}
-Here we achived the reusability but now Class Radio have all the traits which
Class Transmitter have in
it unnecessarily and "NOW CLASS Radio is a class Transmitter also".
Case 2:(with composition)
e.g. class Transmitter{
public void frequency(int hrtz){}
public void tune(double power){}
public void control(String status){}
}
class Radio{
Transmitter t;
public boolean on(){
t = new T();
t.frequency(93.5);
}
public boolean off(){}
}
-Here, only necessary method we reused in our class to complete the functinalities
of on() method.

-----------------------------------------------------------------------------------
-------------------
Date: 08/11/2019
-----------------
- SDP has 3 design principles:
1.Favour Composition over Inheritance.
2.Always design to Interfaces, not to Concrete class.
3.Code should be open for extension and close for Modification.

-Going with Inheritance:


-We can say inheritance will be used for EXTENSION rather than RE-USABILITY.
--Why it is called as Extension?
-When we use extends keyword for our class then all the functionalities will come
to our class and it
makes our class same as that class and we can also add more functionalities into
our class.
-When to use Inheritance?
--Let's say:
1. If we have only .class file and we do not have Source code and we want to use
that class,
Solution: Then we will inherit that class and our new class will become Child class
that means it will
be same as class present in .class file.

2. -Specialization -Generalization -Realization


eg.
class Printer{
void on(){}
void off(){}
}

class InkjetPrinter class LaserPrinter{ class DotmatrixPrinter{


extnds Printer{ extnds Printer{ extnds Printer{
void checkInk(){} void checkCartiadge(){} void checkRibbon(){}
} } }

-----------------------------------------------------------------------------------
-------------------
Date: 09/11/2019
-----------------

--Why Favouring Composition over Inheritance:


1.In most of the use cases it is obsereved that the composition is commonly get
used.
2.Most of the OOP languages does not supports multiple Inheritance.
3.In inheritance classes will become more Fragile as compared to Composition.
4.Testability is difficult in Inheritance.

2.
--We can achieve everything in composition whatever we are going to achieve in
Inheritance.

--We can also modify (extend) the features in existing method by using Composition.
1.**e.g. Using inheritance how we extend the feature:
class A{
int m2(int i){
//logic
return 3;
}
}
class B extends A{
//Override
int m1(int i){
//logic change
super.m2(i);
return 4;
}
}

2.**e.g. Using composition how we extend the feature:


--To achieve this we will do:
class A{
public int m2(int i){
//logic
return 3;
}
}
class B{
A a;
public int m1(int i){
a = new A();
a.m2(i);
//LOGIC changed
return 4;
}

3. What is Fragile?
--Something which is very sensitive and easily breakable is known as Fragile. Like
if a glass will
get small dent then complete glass will get breaked.
Like that Fragility occurs in our code also.

-----------------------------------------------------------------------------------
-------------------
Date: 11/11/2019
-----------------

-When we going with inheritance the fragility will be more because if we do some
changes in base class
it will affect to all dependent classes.
e.g.
class A{
//suppose we are changing the datatype here int -> double

double m2(int i){


//logic
return 3;
}
}
class B extends A{
//Override
int m2(int i){ //this all code will not work
//logic change // we have to change int to double
super.m2(i);
return 4;
}
}
class C{
B b;
public void m1(int x){ //this code also will not work
b = new B(); // we have to change int to double
int k = b.m2(x);
System.out.println(k);
}
}
class Test
{
public static void main(String[] args)
{
C c = new C();
c.m1(10);
}
}
================>>>> It will give us runtime Exception:

Exception in thread "main" java.lang.NoSuchMethodError: A.m2(I)I


at B.m2(B.java:5)
at C.m1(C.java:5)
at Test.main(Test.java:6)

--So in Inheritance the classes will become more Fragile.

---Where as in composition classes will not become more Fragile. It will be less
fragile because we are
typecasting the type and other will be treated as that only.
e.g.
class A
{
double m2(int i) //if we change this to double from int
{
return 10;
}
}

class B
{
int m2(int i)
{
A a= new A();
int j =(int)a.m2(i); // we will typecast here
return 20; //no further modification required
}
}

class C
{
void m1()
{
B b = new B();
int k = b.m2(10);
System.out.println(k);
}
}

class Test
{
public static void main(String args[])
{
C c = new C();
c.m1();
}
}

--So we can say that Composition is less Fragile.


-----------------------------------------------------------------------------------
-------------------
Date: 12/11/2019
-----------------
-Revision
-Testability
-code coverage
-mock classes

3.Testability:
e.g. In our team me and my teammate wants to work parallaly then we will first make
skeleton of our
classes and everything.
Suppose,
Mike will write Engine class
Sriman will write Car class

So till the engine not completes Sriman can't write Car class, but if we have
abstarct class of engine
based on the method defination sriman can proceed with code.
e.g.
abstarct class Engine{
int ignite(int mode){
return 0;
}
}
//mock class
class TEngine extends Engine{
int ignite(int mode){
int status =ignite(mode);
return mode;
}
}
class Car extends TEngine{
void accelarate(int mode,int speed){
int status =0;
status = ignite(mode);
if(status == 0){
System.out.println("Engine started... Taking the initial
Speed...");
} else if(status == -1){
System.out.println("Ignition not proper... Not Able to start...
Retry");
}else if(status == -2){
System.out.println("Retry failed... Engine not able to start in
this mode...");
}else if(status == -3){
System.out.println("Maintainence Required... Please do not
retry...");
}else if(status == -4){
System.out.println("Engine Dead...");
}
}
}
//test class
class Test111
{
public static void main(String[] args){
Car car = new Car();
car.accelrate(-4,50);
}
}

-Mock class: This are the dummy classes which is useful for programmer in
parallel devlopment if the
logic of main class is not complete and we can use this class to implement our
class.

-Code coverage: When we are writing the test cases and each and every line and
condition is tested then
we can say that 100% code coverage we achived.

-----------------------------------------------------------------------------------
-------------------
Date: 13/11/2019
-----------------

/*
Modes:
0- Automatic Transition
1- Manual Transition
2- Auto Driver
3- Cruize mode
4- Colision Control

Status:
0- Success
-1- Failure..Retry
-2- Mode not Supportes
-3- Maintaince required
*/
abstract class Engine
{
public String ignite(String mode){
return "no mode selected yet";
}
}
class TEngine extends Engine
{
public String ignite(String mode){
return "no mode selected yet";
}
}
class Success extends TEngine
{
public String ignite(String mode){
return "Successful Ignition";
}
}
class FailedIgnition extends TEngine
{
public String ignite(String mode){
return "Failed Ignition";
}
}
class Maintainance extends TEngine
{
public String ignite(String mode){
return "Maintainance Required";
}
}
class Car extends Success //here everytime we need to change the class
for testing
{ //that's wht testability is less here in inheritance
public void accelrate(String mode,int speed){
String status = null;
status = ignite(mode);
if(status.equalsIgnoreCase("Successful Ignition")){
System.out.println("Successful Ignition ... With Mode:::
"+mode);
}else if(status.equalsIgnoreCase("Failed Ignition")){
System.out.println("Failed Ignition ... With Mode:::
"+mode);
}else if(status.equalsIgnoreCase("Maintainance Required")){
System.out.println("Maintainance Required please push your Car to
garage. ... With Mode::: "+mode);
}else{
System.out.println("Mode not Supported");
}

}
}
class Test1
{
public static void main(String[] args)
{
Car car = new Car();
car.accelrate("Colision control ",10);
}
}

-----------------------------------------------------------------------------------
-------------------
Date: 14/11/2019
-----------------

-Why Mock classes?


--When we want to test the logic of our class then if we directly took the return
values of main class
(DEPENDENT CLASS)and we start testing, then if that class have any bug/test Failure
our test cases also
give the wrong result and our expected result will not match.
--In this case we have to create MockClass based on MainClass that returns the
possible return values
and based on that MockClasses we have to further proceed with our Test Cases.

--Always we have to take the seperate Test Case/Class (for per Unit) in the way by
which our each and
every fuctionality will get covered. That is called unit testing.

--Comoposition will make Testing easy:-


e.g.
//this will be implemented and tested seperately by this class devloper
abstract class Engine
{
int ignite(int mode){
return 0;
}
}
/*
Each fuction will be tested seperately (as a unit)because if we extends the class
which is having all
logic in it then the bug from the logic will be carried in our test cases and we
can not found where
problem is occuring
*/
class FailedMockEngine extends Engine
{
int ignite(int mode){
return -1;
}
}
/*
So for every condition there will be separate mock class will present which will
extend the class which
is having logic
*/
class SuccessMockEngine extends Engine
{
int ignite(int mode){
return 0;
}
}
class MaintainanceMockEngine extends Engine
{
int ignite(int mode){
return -2;
}
}
class ModeNotSupportedMockEngine extends Engine
{
int ignite(int mode){
return -3;
}
}
/*
By using composition we will take the abstract class Engine as a (SUPER
Class)reference as a attribute.
Then parametrized constructor is created for Car class which will take MockEngine
as a parameter while
runtime.
And the overridden method will get called from the (CHILD Classes) so we achieve
Runtime Polymorphism.
Based on the output of the overridden method (Status i.e. retrun 0,-1,-2,-3) logic
will run
*/
class Car
{
Engine engine;
Car(Engine engine)
{
this.engine = engine;
}
public void acclerate(int mode,int speed)
{
int status = 0;
status = engine.ignite(mode);
if(status == -1){
System.out.println("Failed to Start... Retry..!!");
}else if(status == 0){
System.out.println("Engine Successfully started!!");
}else if(status == -2){
System.out.println("Maintainance needed!!");
}else if(status == -3){
System.out.println("Mode Not Supported ...");
}
}
}
/*
For each type of test we just have to refer and create Object of that
MockClassEngine
And then we will pass that reference as a argument to the Car class Constructor
At the runtime it will choose the overridden ignite() of reference classses and it
will return the
status and based on that Status will be displayed
*/
class Test1
{
public static void main(String[] args)
{
Engine failedMockEngine = new FailedMockEngine();
Car car1 = new Car(failedMockEngine);
car1.acclerate(0,1);

Engine successMockEngine = new SuccessMockEngine();


Car car2 = new Car(successMockEngine);
car2.acclerate(0,1);

Engine maintainanceMockEngine = new MaintainanceMockEngine();


Car car3 = new Car(maintainanceMockEngine);
car3.acclerate(0,1);

Engine modeNotSupportedMockEngine = new ModeNotSupportedMockEngine();


Car car4 = new Car(modeNotSupportedMockEngine);
car4.acclerate(3,1);
}
}

-----------------------------------------------------------------------------------
-------------------
Date: 15/11/2019
-----------------
-Compositon also have some problems.
i.e.Tight coupling.

-----------------------------------------------------------------------------------
-------------------
Date: 17/11/2019
-----------------
=When we want to reuse the functionality of another class then we divide them into
modules and that is
called modularity.
=Modularity is useful for achieving reusability.
=For reusability one class should talk to another class that means no class can be
isolated so here we
can say one class is dependent on another class.
=For talking to another class we have 2 ways:
1.Inheritance(IS-A relationship)i.e. extending/enhancing the functionality of super
class
2.Composition(HAS-A relationship)i.e. using the part of functionality.

-Inheritance has more problems as we discussed earlier in Statergy DP.


-Now, when we are going with composition then again we are facing the problem of
Tight Coupling.

NOW WHAT TO DO????????????????


??? NO COMPOSITION, NO INHERITANCE, then what??????????

=Let's discuss what is Tight Coupling.


e.g.
class A{
int m2(int i){
return 31;
}
}
class B{
A a;
void m1(int k){
a =new A();
int j = a.m2(10);
}
}
-So, here in above example class B is dependent on m2() method of class A.
-If we remove or change the class A then class B will get affected by it.
-Here we can say that tight coupling is between class A and class B.

-Tight coupling has the 4 major problems:


1.The complexity of code will be more as if we want a change in the class on which
other classes are
dependent then we have to "FIRST ANALYZE HOW MANY CLASSES ARE DEPENDENT ON THAT
CLASS And
then WE SHOULD MAKE THE CHANGES." that is where we will face more complexity while
Analyzing.

2.As analyzing will become complex the changes will take more time.

3.To fix such complex and lengthy fixes the cost required is more.

4.Maintaince will be difficult and chances of getting more bugs.

-So we can say that when the classes are dependent on each other or coexitance
between class is more
will define they are tightly coupled.
-So overall we should avoid tight coupling while going with Composition.

-Where in Inheritance the coupling between the classes will not occur as when we
are extending our class
from super class they both will become same and change/removal of method in super
class specifies that
all the dependent class will not require it. So we can not say coupling is there in
Inheritance.

---How to reduce Tight coupling then and reuse the other class with Loose
Coupling??
#Design Principle 2:
=Always code to Interfaces, never code to Concrete Classes:

e.g.
class A{ //Tight Coupling class B{
int m2(int i){ -------------------------->>>> A a;
return 10; void m1(int j){
} -------------------->>>>a = new A();
} a.m2(35);
}

--If we want to change class A to class C

e.g.
class C{ //Lot of Changes class B{
int m2(int i){ -------------------------->>>> C c;
return 10; void m1(int j){
} -------------------->>>>c = new C();
} c.m2(35);
}
**********WE end up with lot of analyzation and changes which is very tedious.

-To over come this we will not directly talk to classes.


Solution: Instead we will write Interface.
e.g.
public interface IStudent {
String name(String sname);
int sno(int rno);
double avgMks(double[] mks,int total_sub);
}

public class StudentImpl implements IStudent {


@Override
public String name(String sname) {
return sname;
}

@Override
public int sno(int rno) {
return rno;
}

@Override
public double avgMks(double[] mks,int total_sub) {

int sum = 0; // initialize sum


int i;

// Iterate through all elements and add them to sum


for (i = 0; i < mks.length; i++)
sum += mks[i];
return sum/total_sub;
}
}

public class Result {


IStudent student;
void resultDisplay(String name,String sno,double[] mks){
student = new StudentImpl2();
String stud_name = student.name("Abhi");
int roll_no = student.sno(21);
double avg =student.avgMks(mks,5);
System.out.println(stud_name);
System.out.println(roll_no);
System.out.println(avg);
}
}

public class TestResult {

public static void main(String[] args) {


Result r1 = new Result();
double[] d = {30,20,50,60,40};
r1.resultDisplay("Abhi","101",d);
}
}
-So if my class get changed I just need to change the derived class reference.

-----------------------------------------------------------------------------------
-------------------
Date: 18/11/2019
-----------------

-What type of changes are affecting the dependent class?


-Basically we make 3 types of changes in our classes
1.interface change:(this affect the dependent class)
-which means change in the method signature
2.programatic change(this does not affect)
-change in the logic or algorithmic change for optimization
3.chnage in module/class(this also affects)
-we did not make major changes in our existing classes, for this we will rewrite
the class, then the
change in class affect on dependent class.

also code should be open for extension and closed for modification.

-----------------------------------------------------------------------------------
-------------------
Date: 19/11/2019
-----------------

-revision of above 3 points and example of each.

-Is change in the interface method/method parameter will get called as Tight
coupling????

==No.
Because we only change the interface method when there is change in the
requirement.
Otherwise we will not make the changes so it won't get called as coupling.
We also can avoide the changes in interface but we will see that in upcoming
classes.

-----------------------------------------------------------------------------------
-------------------
Date: 20/11/2019
-----------------
example: Vehiccle and other classes using statergy DP

-----------------------------------------------------------------------------------
-------------------
Date: 21/11/2019
-----------------

1.==What if I use Inheritance for loose coupling? and if we Don't code to


Interface?

-What we are doing with 1st,2nd priciple of Stategy DP:


-Favor composition over Inheritance..Always code to Interface never design to
concrete classes.
Question arises====What happen if design to Concrete class and not favoring
composition.
Ans:
1.class B is not a candidate of Inheritance.
2.B is became dead code.
3.All devlopvers unaware that "B" is not valid for use. We cant mark it as a
dead or also we
cant say not to use it.
e.g.
class A {
B b; //We are dierctly talking with class B, i.e. It is not following
any contract
void m1(int j){ //So if B removed it will affect class A because C is
extending from B
that's why "B" is not valid candidate for Inheritance
b = new C(); //we changed the Class but below are the problems.
b.m2(j);
}

class B { //Class B is became DEAD CODE. Because of C is having optimized


Code
int m2(int j)
{
return 34; //Other devlopers are unaware about it
} //They might end up with using class B
}

class C extends B{
int m2(int j){return 56;} //new Optimized logic
}

2.==Can we achieve loose coupling via inheritance?


Ans.No.
if we try to do so..
e.g.,
--------CASE-1---------------
class A{
int m1(int i){return 35;}
void m2(int j){}
int m3(int k){return 36;}
}
//Suppose we want to reuse m1(),m3()..via Inheritance:

class B extends A{
//Here we need only 2 methods but if we inherit it then it will get all three
methods.
//***So what is wrong with this?
/* Suppose if I got the requirement of method with different method signature
int m2(int j){return 44;}
*/
SO WE CAN NOT DUPLICATE The Method as overriding with Different RETURN TYPE/ANY
CHange.
}
--------CASE-2------------------
//Can we declare the attributes/variables by Inheritance in Super class?
=Yes we can, because the super class Attributes will not get inherit to the sub
class.
-If we want to access that variable we have to use super.attributeName; then it
will be availble to
our class.

-So declaring attributes will not make anything with Inheritance but if we extend
then in terms of
method we can not declare it again if you want to do so it should be same i.e.
Overriding.
e.g.
class A {
int i;
int m1(int i){return 35;}
void m2(int j){}
int m3(int k){return 44;}
}
class B extends A{
int i = 10;

void m4(){
System.out.println(this.i);
System.out.println(super.i);
}
}

3.==Can we use Abstarct Class instead of Interface?


-In our requirement we just had the full abstarct method and none of the concrete
method is there.
-So it leads to take Interface instead of Abstract class as it is 100% pure
abstract class.

-----------------------------------------------------------------------------------
-------------------
Date: 22/11/2019
-----------------
Revision
+ Google Weather Example started

-----------------------------------------------------------------------------------
-------------------
Date: 24/11/2019
-----------------
//Our Own Interface
public interface IClimateReporter {
public double temprature(int zipcode);
}
public class GoogleClimateReporter implements IClimateReporter{
//We will make one class which satisfy the contract between me and Client

Forecast forecast; //Attribute of class which will have Third Party Class
// and we will override Interface method
//We will not directly talk with that

@Override
public double temprature(int zipcode) {
forecast = new Forecast();
double temp = forecast.weatherReport1(zipcode);
return temp;
}
}
//Third Party provided Class/Interface
public class Forecast extends GoogleForecastAnalyzer{
@Override
public double weatherReport(int zipcode) {
// TODO Auto-generated method stub
return super.weatherReport(zipcode);
}
}
public class WeatherGadgetServlet extends HttpServlet {
@Override
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {

PrintWriter pw = null;
int zipc = 0;
pw = res.getWriter();
res.setContentType("text/html");
IClimateReporter icr = new GoogleClimateReporter();

zipc = Integer.parseInt(req.getParameter("zip"));

double current_status = icr.temprature(zipc);


String tempt = Double.toString(current_status);
pw.println(tempt);
}
}

For this google use case we will third party API provided by the Google/Honeywell.

-----------------------------------------------------------------------------------
-------------------
Date: 25/11/2019
-----------------
Use Case 2:

public interface IMessageWriter {


public String convert(String message);
}

public class MessageWriter {


IMessageWriter messageWriter;

public void htmlConvert(String message) {


String htmlMessage = null;
messageWriter = new PDFMessageConverterImpl();
htmlMessage = messageWriter.convert(message);
System.out.println(htmlMessage);
}
}

final public class HTMLMessageConverterImpl implements IMessageWriter {

@Override
public String convert(String message) {
String htmlMessage = null;
htmlMessage = "<html><body>" + message + "</html></body";
return htmlMessage;

public class PDFMessageConverterImpl implements IMessageWriter{

@Override
public String convert(String message) {
String pdfMessage = null;
pdfMessage = "<pdf>"+message+"</pdf>";
return pdfMessage;
}

-----------------------------------------------------------------------------------
-------------------
Date: 26/11/2019
-----------------

=In above example we are following Statergy Design Pattern and we achieving almost
complete loose
coupling but still there somewhat coupling is there.

=Where the coupling is and How it is coming here?

public class MessageWriter {


IMessageWriter messageWriter;

public void htmlConvert(String message) {


String htmlMessage = null;

**************//Here Still we are modifying the code


messageWriter = new PDFMessageConverterImpl();
//Here it is Dependent on PDFMessageConverterImpl
//that is coupling i.e.very very less
htmlMessage = messageWriter.convert(message);
System.out.println(htmlMessage);
}
}
==Because of that we are Facing two Problems:

1.The MessageWriter class have to create the Object and for that we need fully
qualified name of the
class/concrete class name and "Tight Coupling problem Arises".
By this Myclass have to create or My class should know the implemetation logic
and it will be exposed.

2.Sometime the object Instantiaion may get Complex and the change in the object
creation in any
class will affect everywhere in code.

e.g.
class A{}
class B{
B(A a){}
}
class C{ class Test{ main(String[] args){
C(B b,A a){} A a = new A();
} B b = new B(a);
C c = new C(b,a);
}}

-Here to create Object of the C we need to create obeject of class A & C and to
create object of the
class B we need to have Object of class A.
-In this way it is becoming complex and if suppose if the code is modified like,
e.g. class B{
B(A a,C c){}
}
then, we again need to change all the code
& If we want the same obejct again, then again we need to write all code and code
will get duplicated.

===To avoid this what we should do?


-We have to avoid creation of Object in my class.
That means in class MessageWriter we will not create any "new ClassName" i.e. it
won't create any Object.

And we will get the Object from FactoryDesignPattern.

-----------------------------------------------------------------------------------
-------------------
Date: 27/11/2019
-----------------

=What problem arises after going with Statergy DP?


-When we are using the Implementation class then
1.My class have to create the Object of the class then My class must need to know
the Concrete class
name and it's getting tightly coupled again.
2.Sometime the Implemenation logic may complex and if the object creation change
for any class it will
affect the entire class.

=What is Factory Design Pattern?


-When we want to abstract the object creation logic or,
When the object creation is very very complex or,
When we do not want to repeat the code of object creation in every class where it
is needed or
When we want to go for more loose coupling where we need not expose to give
concrete class and my class
will not contain instantiation logic,
in this case we will go for factory method it will give us that class Oject using
static method inside
it.

=What is the Scope of methods? What is the Scope of attributes?


-Scope of the methods is only up to the class level.
-The Scope of the attribute is up to the Object level.

=After creating object what it have?


-It have nothing, it will be an empty object.

=Why static method?What is the use of Static method?


-When we have only methods inside our class and there is no attributes inside our
class then by
instantiating the Object of that class will give nothing as the methods are only
available to class
level not to object level, if we create the object also it will not get used and
Garbage Collector,
will collect unused Object, so to call that method directly by using ClassName.MN()
we will use Static().

=In our class what we are taking before Factory DP to Instatntiate?


-We are taking Fully Qualified class name/ concrete classes which makes Tightly
coupling.

=What 2 advantages of Factory DP?


-1.It will abstarct the Instantiation Logic and classes are not exposed and Tight
coupling avoided.
-2.If there are changes in instantiaion logic we just have to modify Factory class.

= Why we took Interface as a return type in Factory method?


-To take any Impl classes.

= In our class what we have to take after implementing Factory DP to instantiate


the object?
-We have to take the "logical names" of the classes.

=What Factory classes have inside it?


-public static Method which returns the Object.

=Why factory classes are util/helper?


-Because they are helping us to get an readymade Object that's why we can call it
as Helper or Util
class.

=Are we achiving complete loose coupling via Factory method?


-No we are Still having very very less amount of coupling.

=Why we are unable to make complete loose coupling via help of Factory dp?
-Because we still need to use logical name of the class.

=Should we avoid these less coupling or we have to Ignore this?


-We have to avoid this.

-----------------------------------------------------------------------------------
-------------------
Date: 28/11/2019
-----------------
=My class will not create object also will not use Factory
=We will use setter method
=The Test class need MessageWriter so required class will create Object
=Dependancy

-----------------------------------------------------------------------------------
-------------------
Date: 29/11/2019
-----------------

-When Test class is creating object then also coupling is there.

-Because the instantiaion process is still by using new keyword and the class name
is been exposed.
-Also we are taking the name of the class in Test class that will again making it
coupled.
-To avoid this coupling we will take Factory class name and that static method so
we can achieve loose
coupling.

-But still there is very very very less coupling is still availble as we are
dependent on Factory
indirectly as we are taking the logical name so Test class is dependent on Factory
class.

-----------------------------------------------------------------------------------
-------------------
Date: 02/12/2019
-----------------

-Revision
-Delivery of code in Production
(see diagram of Delivery of code in Production.png on desktop folder)

-----------------------------------------------------------------------------------
-------------------
Date: 03/12/2019
-----------------
-When QA Started Testing over the application provided by devlopers QA has to find
as many bugs as
possible.
-When we perform unit testing and check in our code to source code repository QA
will work as per the
cut off date and once everyone commit there code then there is one lead in Testing
team who will receive
the email regarding that final commit has been done and the code freez time has
been started then
QA's can start working over it and devlpoer will pause there work.
-When Testers found the bugs first they have much sure about that bug before
reporting in case it is
really a bug then they will report it.
-Bugs are not directly reported to devlopers, instead Testers use different tools
for bug reporting e.g.
Bugzilla,BugHerd,Mantis Bug Tracker,Marker,DoneDone,etc.
-This tools are very useful to give the detailed and structured information about
the bug occured in
application.
-The testers are not aware about which devloper worked on which module so when bugs
need to reported
in devlpoer team we have one devlpoment manager so in the test report they assign
the bugreport to
devlopment manager and then devlopment manager will identify the module on which
the co-workers worked
on and then devloper can start the bug fixing.
-When bug is reported to devloper, then he need to analyze first that is this
really a bug? or the QA's
have been miss interpreted the actual requirement.
-Once we anylyze report then if there are multiple bugs then we need to start
resolving it via priority,
severity, and status of the bug based on this we can start debugging it.
-The testers will also provide us the reproducing procedure of the bugs so we can
make our code tested
and we will get the root cause of that bug.
-Once we fix the bug devloper needs to do the unit testing and then we also have to
add comments in bug
report that how we worked on that bug and then we need to commit our code.

=Bug Report:
title of the bug:
description of bug:
#what has been tested
#actual
#expected
#reproduce procedure
reported by:
Assigned to:
version:
Status:
priority:
severity:
project name:
module name:

Comments

-----------------------------------------------------------------------------------
-------------------
Date: 04/12/2019
-----------------
-----------------------------------------------------------------------------------
-------------------
Date: 05/12/2019
-----------------

-When there is very less coupling then also we should not avoide it, why because
the change which seems
very minor in devlopment that change will affect over the retest, recompilation,
re-run, and deploying
that again and again which is time consuming and costly.
-e.g.
class A{
int i;
public void work(){
i=10;
//some operation
}
}
A a = new A();
a.work();
-Here the i value is "10", that is fix for it suppose if we want to change it to
"20", then again we
need to hardcode it and just changing it will not applicable for that we also want
to compile it again,
and also we have to re-run so in this case we do not have to took the values in
this way.
-Suppose if we take the value from external files i.e.Text file:
- class A{ abc.txt
int i; 10
public void work(){
i = new FIS("abc.txt");
}
}
-Here in the text file the i value is 10.
-If suppose I want to change the value to 20 just have to modify the text file and
because of it I don't
have to modify the code so Testers also not have to again test it also not want to
compile and re-run it.

-We can apply this same to our classes so we will not create the object instead of
that we will take it
from external file.
-We can not directly take the class names inside our text file because again we
haveto write complex
logic and code by which our classes will exposed to instantiaon logic or we have to
use logical name.
-We will not use the text file here because we again have to write logic to retrive
class names from
that text file which is again complicated.

public class Test {


public static void main(String[] args) {
IMessageWriter messageWriter=null;
messageWriter = new HTMLMessageConverterImpl();
//Here I have to change the Object Instantiation logic
MessageWriter msgWriter = new MessageWriter();
msgWriter.setMessageWriter(messageWriter);
msgWriter.htmlConvert("Hello Statergy DP");
}
}

-We have to take the external file as properties file which is special type of file
been use for storing
key & values seperated by "=" and having extension .properties
-To read the data from this file we can also use Map collection becaue is Map the
using keys we can
use it for instantiation logic. But we will not use Map here.
-Instead we can write them into "key","value" format and to rerive that key value
we will not use
"MAP Collection" because it provide us the "Object Format"
by which we will again end up with tight coupling.

-To retrive the key nd values from .properties file we will use Properties
collection which will load
the file inside it and it will fetch the data from file in "String" format
directly.
e.g. Properties p = new Properties();
p.load("classes.properties");
-So then we can operate over the key's:
p.getProperty("accountManage");
-Here we will get the "A" class.

Suppose, we have classes like:


class A for accountManagament key value
accountManage=com.app.A
(Fully qualified name required)
class B for balanceSheet key value
knowBalancesheet=com.app.B

class C for accountManagament key value


compoundInterset=com.app.C

class D for accountManagament key value


deductionOfTax=com.app.D

-In this way we can simply work with the functional name of a class which is "key"
and not directly
representing the class by which if we change the class name also we only related to
the functional name
so we just have to worry about the requirement not on the values which determines
the class.

-----------------------------------------------------------------------------------
-------------------
Date: 06/12/2019
-----------------
-To take the functional name of the class in our program we have to write external
files.
-That files are basically in non java formator we can simply call it configuration
files in which the
program cfgs are written.
-In this case we are using .properties file and we are writing classes in key and
value formats.
-And we also don't have to expose the class name and hide/abstract the complexity
of creating object
so we are taking the help of helper classes such as Factory classes.
-We will take AppFactory class which will load the class from Properties collection
which can directly
process the Strings which are there in properties file in KEY=VALUE format.
-e.g.
public class AppFactory {
public static Object createObject(String lClassName) throws
FileNotFoundException, IOException,
ClassNotFoundException, InstantiationException,
IllegalAccessException
{
String className = null;
Class clazz = null;
Object obj = null;

Properties props=new Properties();


props.load(new FileInputStream("F:\Java\Study\Spring
Core\StatergyPattern\src
\com\sp\common\app.properties"));
className = props.getProperty(lClassName);
clazz = Class.forName(className);
obj = clazz.newInstance();
return obj;

}
}

-----------------------------------------------------------------------------------
-------------------
Date: 07/12/2019
-----------------
-While devloping the code we are loading the external file by using load() of
Properties, there
we are giving the "Absolute Path"(complete path).
-If we are giving that path that means if I want to change the location of the file
or folder again
I have to modify the path.
-In eclipse the Source file path is set over the "src" folder where all .java files
are present in the
IDE.
-Eclipse or any IDE will seprate the Production Code(which has been deliver to
customer/client) at later
point of time in "bin" folder. i.e. all the which is need to run/build our
application i.e.(.class) files.
-While sharing the code with another devlpoer we might won't have the same
directory structre on different
computers in team, so in that case our external files will not get located
according to path we have
mentioned.
-We have to always take the path from "bin" instead of "src" because when we gave
the JAR file to
customer we will not provide the source code we will give the production code
i.e."present inside bin"
so when customer will run the app it will point to bin.
-Also we can make the "Relative path"(which is changable) i.e."F:\Java\Study\Spring
Core\StatergyPattern"
inside a String CLASS_PATH constant and append it to later part
i.e.src\com\sp\common\app.properties
so other programer just have to modify the constant which is easy way also.
-But while doing that we are Hard Coding the path that means if other programmer
has to change it then
again we have modify the code inside source file and again need to recompile it and
again redeploy
instead of that alternaive is we can again take that in one more external file and
whenver path is
change again we just have to modify that file.
-Also when I handover the application to the customer then customer might have
different directory
and he will work on another folder but he won't put my .class files in another
folder as the deployed
JAR files will have from "/bin/" folder.
-So here we just have "___/___/___/com/sp/common/app.properties" this path the
first 'directory',
'folder','ProjectName', is not avaible there.
-So we can get them as when JVM loading the class it will take the .class file so
using ClassFileName
and getClassLoader file we can get the "prefix" information that is:
F:/Java/Study/Spring Core/StatergyPattern/bin
and the rest of the part we will provide by: .getResourceAsStream() method.
-So total it will become:

(AppFactory.class.getClassLoader().getResourceAsStream("com/sp/common/app.propertie
s"))
F:/Java/Study/Spring Core/StatergyPattern/bin--->then-
>com/sp/common/app.properties
(WE GET IT FROM JVM)

Properties props=new Properties();

props.load(AppFactory.class.getClassLoader().getResourceAsStream("com/sp/common/app
.properties"));

-So here we are not hardcoding and also our external file will get easily fetched.

-----------------------------------------------------------------------------------
-------------------
Date: 08/12/2019
-----------------

-Devloped Spring application without Spring.


-We learned that how to make application completely loosley coupled.
-We have to apply Statergy Design pattern.
-We have to make our classes 100% loosely coupled.
-We never have to write any instantation logic inside our classes or not have to
pull any object.
-We learned that using setters we will set the object.
-We learned how to set the path for Absolute path and Relative path.
-Also we will use Factory method to create our object so we can hide the complexity
of creating object
and we will not exposed to any classnames.
-We will use external files to set the properties.

-We will now convert this application to Spring Core Application.

-We will use Statergy Design pattern for our classes.


-We will make them completely loose coupled.
-We will use the setters to set the object.
-We will make use of BeanFactory (I) and XmlBeanFactory(C) as a Implementation
class to get the object.
So the boiler plate logic we are writing Spring will write for us.
-We have to give this information to Spring not by using "Properties file" we will
use "XML" file as
it named as Spring Bean Configuration file. We will name it as "application-
context.xml"
-We will provide the bean defination that is classes information we have to tell to
Spring inside
root tag: <beans><bean id="logicalName"
class"fullyQualifiedClassName"></bean></beans>
-We have two options for getting that config file like: Absolute Path and Relative
Path
-Spring have Resources(I) and two Implementaion classes FileSystemResource(C) for
Absolute path and
ClassPathResource(C) for Relative path.
-We will use .getBean() method and we will pass the logical name as a parameter
which is id in bean
definition and typecast or will Generics of the Object type which we need.

-----------------------------------------------------------------------------------
-------------------
Date: 09/12/2019
-----------------

public class StatergySpringTest {

public static void main(String[] args) {


IMessageConverter messageConverter;
MessageWriter messageWriter = null;

BeanFactory beanFactory = new XmlBeanFactory(new


ClassPathResource("com/ss/common/application-context.xml"));

messageWriter =
beanFactory.getBean("messageWriter",MessageWriter.class);

messageConverter =
beanFactory.getBean("pdfMessageConverter",IMessageConverter.class);

messageWriter.setMessageConverter(messageConverter);
messageWriter.writeMessage("Welcome to Spring");
}
}

-----------------------------------------------------------------------------------
-------------------
Date: 10/12/2019
-----------------
-In our code still if we have to change the pdf to html we have to modify the
source code of class.
-Then that is not recommanded to set dependencies in the java code.
-In above code for messagareWriter attribute the we need object of messageConverter
that is html or pdf
message converter object which we have to orvide from outside of the java class
that is from config file
-In this case we will not set the object to setter method and also not set the
Implementation class
object to messageConverter directly in java code.
-We will use setter Injection inside config file to do this.
<bean name="messageWriter" class="com.ss.beans.MessageWriter">
now messageWriter needs the IMessageConverter messageConverter;
................---> This Object
So instead of setter we will use <property> which will act as a
"SetterInjection"
<property name="messageConverter" ref="htmlMessageConverter"/>
here we are setting the object attribute here we are setting the dependancy

</bean>

-In this way we also can use Constructor for setting the Oject so while
Initialization it will set
the dependecny of the Object.
-So what Constructor will do: It will intialize the parameters which we define
inside it.
So in MessageWriter constructor we will tell that I need a messageConverter
object.
So we can manage the dependecies by constructor Injection

<bean name="messageWriter" class="com.ss.beans.MessageWriter">


now messageWriter needs the IMessageConverter messageConverter;
................---> This Object
So instead of setter we will use <property> which will act as a
"SetterInjection"
<constructor-arg name="messageConverter" ref="htmlMessaageConverter"/>
here we are setting the object attribute here we are setting the dependancy

</bean>

-Flow of the Spring:

BeanFactory beanFactory = new XmlBeanFactory(


new ClassPathResource("com/ss/common/application-
context.xml"));

-Whenever we are creating the BeanFactory which is Interface we have to take the
implementation classes
so we are taking here XmlBeanFactory which needs a path and for that it will take
the path from Resource
-Then the Resource Object will be created first by using the absoulte/relative
path.
-Then that resource object with location "path" of the configuration file will give
the Spring bean
configurtion file to the XmlBeanFactory.
-The config file will consist of bean defination that is the class information
which need to instantiated.
-The Factory will read and load the bean defination and load the file (application-
context) to the
IOC Container.
-The IOC is a "PRINCIPLE" by which we can 1.Manage the lifecycle of an Object and
2.We can make our
objects to collaborate.
-The IOC Container will be loaded into the JVM memory of the RAM memory of system
then we will have
a space for our application inside the JVM memory.
(refer IOCflow.png)
-The IOC Will check the loaded XML file
1.Well formed or not(all tags are open and closed properly or not)
2.Valid or not(all attributes of xml is as per SPRING DTD or not)
-If not then it will throws the exception
-If it is valid then it will creates the in memory metadata in the internal cache
of IOC container.
The internal Cache have the key = value of the object
messageWriter = MessageWriter class Object
htmlMessageConverter = HTMLMessageConverterImpl class Object
pdfMessageConverter = PDFMessageConverterImpl class Object
-So it will not load the configuration file each time either it will look into the
metadata and makes
it faster.
-When we,
getBean("pdfMessageConverter");
.....................
Always this will get checked in in memory metadata
-Once it will find the key then it will create the Object of the class and manages
the lifecycle of it.
-When factory will read the configuration file if it finds the
property/constructor-arg in bean
definiation (setter/constructor injection) then it will manage the dependencies and
make the objects
collabotrative with each other.

-----------------------------------------------------------------------------------
-------------------
Date: 11/12/2019
-----------------
-What is Dependency and Managing Dependecy?
-messageConverter =
beanFactory.getBean("pdfMessageConverter",IMessageConverter.class);
-Here messageWriter wants the pdfMessageConverter or htmlMessageConverter that
means it will need one
out of it but it is not fixed and also if some other class came that also wants any
of it so here the
classes are not changing.
-The changes are in the dependency that is MessageWriter or Other class wants any
of it at any time
then we don't have to change Classes in java code we have to change the dependecy
that to by not
modifying our code by using configuration file we have to manage this dependecy.

-BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource


("com/ss/common/application-context.xml"));
-Here the first ClassPathResource will locate the file from the classpath and this
will take the classpa
th from the IO stream.
-Then this IO stream object will be pass to resource and XmlBeanFactory which needs
the resource in it's
constructor so it can get the file from IO stream.
-When it comes to XmlBeanFactory it will get the location and Spring Bean
Configuration file from the
specified path by the Resource.
-Once it get it then it will check the configuration file that:
1.It is well formed or not-
-<beans>
<a>2000 here the boundries and semantic is checked
</beans>
2.It is valid or not-
-<beans>
<javabean classid="mwr" classname="Mwriter"></javabean> Here it will check it
follows the
</beans> the DTD or XSD provided by Spring
or not

-If it's not well formed or valid then it will throw the exception and terminates
the application.
-If it is well formed and valid then it goes to the JVM Memory and inside it, it
will create a in memory
logical partition and that in memory logical parttion is called as IOC Container or
Core Container.
-Then that core conatiner will have another part inside it that will stores this
data about the config
file data which we can call metadata and it is stored inside again it's logical
memory so it is called
as In Memory Metadata.
-This in memory metadata will consist of bean defination information inside it.
-So when we load this metadata inside IOC conatiner so each time it will not load
or not going to look
inside the Spring Bean Configuration File it will directly look inside in memory
metadata, that is becoz
when we perform the file reading operation over the HardDrive that is the
mechanical device which needs
more processing time to pointing the file retriving the information and then to
operate over it, where
as the RAM is electronic memory type it's more faster than the physical memory
storage.
-And the beanFactory is holding the refernce of IOC container.
-When we call the beanFactory.("beanId",Class.class) , then the in memory metadata
gets readed and as
per the bean defiition the "ClassLoader" will loads the class and "newInstance"
will create the Object
of it.
-When it will creates the Object according to bean definition it will check what
dependency is there
and it will also create that object inject using the "setAttributeName" if setter
injection is performed
-So it will gives us the complete instantiated Object, Container itself manages all
this things.
-When we demands the Object to IOC conatiner internally in another part of IOC's
logical memory it will
creates the internal HashMap with "key" & "value" so all the ID's are assigned to
Objects and when pass
the ID's IOC will return us the Object by pointing key as an reference.
-refer: IOC Flow2.png

-----------------------------------------------------------------------------------
-------------------
Date: 12/12/2019
-----------------

-Comparison between Dependency Pulling and Depedency Injection?


-Both are introduced from very long in the market where everyone is using pulling
for most
of the JEE appliactions using the dependency look up.
-In dependecy Pulling a class needs another another class to complete it's
execution then using dependecy
pulling we have to write code inside our Java classes and we can pull the
dependecies.
-Which have again two types is it:
1.Depenedency lookup
2.Contextual Depenedency lookup

1.Depenedency lookup :
e.g.
class FindTrainSourceToDestination extends HTTPServlet{
service(req,resp){
String source = req.getParameter("source");
String destination = req.getParameter("Destination");

/* -Now here I want to get or persist the source and destination which is
given by user through
the gui and we are storing that into the database.
-So here what we need is the connection with the Database and for that
Connection we have two
ways to get it: 1.By Driver Manager Class
OR BY 2.DataSource Interface

-DataSource and DriverManager are the two basic ways to connect to a database
in a JEE
application.
-The DriverManager is older facility, the DataSource is newer.
-It is recommended to use the new DataSource facility to connect to databases
and other
resources. The DataSource has several advantages over the DriverManager.
-Using the DataSource increases portability. The DataSource enables
connection pooling and
distributed transactions, the DriverManager does not allow such techniques.
-Properties of a DataSource are kept in a configuration file. Any changes to
the data source
or database drivers are made in the configuration file.
-So we just modify the the config files and we will have it without
recompiling it so we will
have the facility of cross platform using DataSource.
-In case of a DriverManager, these properties are hard coded in the
application and for any
changes we must recompile the code.
-Using a DataSource you only need to know the JNDI name.
-The JNDI names are configured in the external file
*/
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/logicalDBName");
Connection con = ds.getConnection("username","password");

}
}
-So using lookup() method we are going to JNDI Registry and finding the database of
the name which is the
logical name of the database stored in JNDI Registry.
-The overall objects required for the connection will be taken care by the
DataSource we do not have to
create or close the connection as DataSource will act as a Manager of it. Also the
DataSource object is
placed inside the application server and it have JNDI registry which contains this.
-So in conclusion we can say that using dependdacy lookup we got the Connection
object and Databsae by
pulling from JNDI Regitry.

-----------------------------------------------------------------------------------
-------------------
Date: 13/12/2019
-----------------
-Contextual Dependency pull
-Servlet config is the one per Servlet Component
-To get Servlet config we have to get first Servlet Context
-So to get this we will first implement HttpServlet and follow one contract that is
we will implement
one init(ServletConfig config) method
-So this cotract as we are doing is known as contextual dependecy lookup
-That means it's pulling the Object over there

-----------------------------------------------------------------------------------
-------------------
Date: 14/12/2019
-----------------

1.Conclusion about Dependency Pulling & Dependecy Injection


-The both are available from very long in the market for making the collaborarion
between objects but
dependancy Pulling is used and it's the traditional way.
-In dependecny pulling we are getting the Object from another class to our class.
-In dependecy lookup we are first search in the public registry bt reference and
pulling the Object.
e.g.Datasource using lookup() inside JNDI Registry.
-In contextual dependency look up we are pulling the Object by following an
contract. This contract
means that we are fetching an private Object which can not be part of public
repository it means it will
be only available to our class.
e.g.Servlet Config Object is availble when we write init() method by implementing
interface so container
is providing the config Object only when we are following the contract hence it is
known as contextual
dependecy lookup.

-So Here in dependency pulling by anayways we have to write the Object pulling
logic inside our java
code which is not recommanded as we are getting tightly coupled and many more
disadvanatges are there
so we are going with dependecy Injection.

-Dependency Injection
-In dependecy Injection we don't write logic for pulling the object even though we
are not taking the
name of the dependent class in our class so we are managing the depdencies from
configuration file which
makes our classes completely loosely couple.
2.Setter Injection
-e.g.
class A{
B b;
void m1(){
b.m2();
}
void setB(B b){}
}
class B{
void m2(){}
}
-So here A class needs B class object so we declared the attribute and wrote a
setter method as we do not
have to write pulling logic or instantiation logic.

BeanFactory factory = new XmlBeanFactory(new


ClassPathResource("com/ss/application-context.xml"));
factory.getBean("");

application-context.xml
.......................
<beans>
<bean id="a" class="com.ss.A">
<property name="b" ref="b">
</bean>

<bean id="b" class="com.ss.B">


</bean>
</beans>
-Here we are taking the refernce of another dependent class as a attribute in my
class and then we are
setting that object using setter Injection.
-The flow is when it finds the class which have to be instantiated it will create
Object for it and then
if any setter injection i.e.property tag is there then IOC Container will check
that Object is availble
in container or not if availble then it will not create Object and if not then it
will create the Object
andinject it.

3.Constructor Injection
-e.g.
class A{
B b;
void m1(){
b.m2();
}
A(B b){this.b=b;}
}
class B{
void m2(){}
}
application-context.xml
.......................
<beans>
<bean id="a" class="com.ss.A">
<constructor-arg name="b" ref="b">
</bean>

<bean id="b" class="com.ss.B">


</bean>
</beans>
-Here first the IOC will look for constructor injection and first make that object
ready it will look
into IOC container if Object is availble it will return or else creates the Object
and then the bean
definition object get created.

4.What is IOC
-IOC is termed as inversion of control.
-That means in dependecy pulling we are pulling the Object of another class so the
class who is pulling
is in need of another object so that is dependent class as it is dependent on other
class object.
-And the class who's object is getting pulled that is Traget class as it is
providing the Object.

-But here in Dependecy Injection the class is niether creating the object nor
pulling the Object infact
there is no logic is written inside that class to pull or cerate the Object so it
will become completely
loosely coupled.
-In dependecy injection IOC Conatiner will push the Object so that means someone is
injecting the object
inside it so here the inversion take place that means the class in which Object is
getting Pushed is
becoming Target class as IOC pushing the Object inside it.
-And the class who's object is been pushed to other class is becoming dependent
class so here the
inversion of control occurs.

5.So Spring how spring is Managing the Dependecy?


-Spring can manage the dependecy by all the four types:
1.Dependency Pulling
#dependecy lookup
#contextual dependecy lookup
2.Dependency Injection
#setter injection
#constructor Injection

e.g.Weather Reporter

-----------------------------------------------------------------------------------
-------------------
Date: 15/12/2019
-----------------
1.What is difference between Setter and Constructor Injection?
-In setter Injection the dependent object is created after creating the target
Object
-In constructor Injection the depdendent Object is created while creating the
target object
-In setter injection the injecting the dependent object is optional.
-In constructor injection dependent object is manadatory to create target object.
-In setter injection we can manage dependency between cyclic dependency.
-In constructor injection we can not manage cyclic dependecy.

2.When should we use which Injection?


-When we don't need dependent object while creating target object go for setter
injection.
-When we need dependent object while creating target object go for constructor
Injection
-When we want dependent object injection as a optional go for setter injection.
-When we want dependent object injection mandatory go for constructor injection.
-When we want to manage cyclic dependency go for setter injection
-When we have no requirement of cyclic dependency go for constructor Injection.

3.Primitive type Injection.


-As we are injecting the Object type to the attribute as a dependent we also can
inject primitive type
attributes to the object.
e.g. private String product_name;
//setter

application-context.xml
<property name="product_name" value="Television" />

4.Collection Type Injection


-As we can manage the Object and Primitve type dependecy we also can manage
Collection type classes
injection.
-Spring Supports 4 types of collection:
1.List
2.Set
3.Map
4.Properties

-List
e.g. private List<String> items;
public void setItems(List<String> items) {
this.items = items;
}

application-context.xml
<property name="items">
<list value-type="java.lang.String">
<value>Mobile</value>
<value>AC</value>
<value>Fridge</value>
</list>
</property>

-Set
e.g. private Set<String> reviews;
public void setReviews(Set<String> reviews) {
this.reviews = reviews;
}

application-context.xml
<property name="reviews">
<set value-type="java.lang.String">
<value>Nice</value>
<value>Great</value>
<value>Awesome</value>
</set>
</property>

-Map
e.g. private Map<String, String> sales;
public void setSales(Map<String, String> sales) {
this.sales = sales;
}

application-context.xml
<property name="sales">
<map>
<entry key="Allen" value="product"/>
</map>
</property>

-Properties
e.g. private Properties designation;

public void setDesignation(Properties designation) {


this.designation = designation;
}

application-context.xml
<property name="designation">
<props value-type="java.lang.String">
<prop key="Manager">Sharma</prop>
<prop key="Head">Varma</prop>
<prop key="Senior Advisor">Shukla</prop>

</props>
</property>

-----------------------------------------------------------------------------------
-------------------
Date: 16/12/2019
-----------------
-namespace

-Bean Alias
-name
-alias tag

S-ar putea să vă placă și