0% found this document useful (0 votes)
88 views

Spring Core

This document discusses Spring Core module which provides fundamental concepts like beans, dependency injection, and inversion of control. It describes how Spring container manages the lifecycle of Spring beans and how dependency management can be done through dependency lookup or injection.

Uploaded by

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

Spring Core

This document discusses Spring Core module which provides fundamental concepts like beans, dependency injection, and inversion of control. It describes how Spring container manages the lifecycle of Spring beans and how dependency management can be done through dependency lookup or injection.

Uploaded by

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

Chapter-01

Spring Core
===================
Spring core Module
===================

- Spring core is a base module in Spring framework. All the modules in the Spring
are developed on top of Spring core module.
- By using spring core module, we can develop only standalone application
- Spring core module is providing fundamental concepts of Spring framework like –
 Beans
 Core
 Inversion of control (IoC)
 Dependency Injection (DI)
 Context
 Expression language

======
Beans
======
- Beans are java objects that are configured at run-time by Spring IoC Container. In
Spring, the objects of our application and that are managed by the Spring IoC
container are called beans

----------------
Java Beans
----------------
- It is a java class developed by following some standards.
- It is always used as helper class to pass multiple values as single object from one
class to another class
The standards are
- Class must be public
- Recommended to implement java.io.Serializable(I)
- All members variables (Bean properties) must be taken as private and non-static.
- Make sure one zero param constructor must be there either given by developer
or compiler. Because sometime framework container create object for java been
internally using zero param constructor.
- Every been properties (non-static variable) should have public setter for
set/modify data of bean properties and public getter for read/access data from
bean properites.
Chapter-01
Spring Core
- In java bean we do not place methods having business logics because java bean is
just data carrier.

Example:
1. public class StudentDetails implements java.io.Serializable{
2. private Integer sid;
3. private String sname;
4.
5. public StudentDeatils(){} // zero param constructor
6.
7. public void setSid(Integer sid){
8. this.sid = sid;
9. }
10.
11. public Integer getSid(){
12. return sid;
13. }
14.
15. public void setSname(String sname){
16. this.sname = sname;
17. }
18.
19. public String getSname(){
20. return sname;
21. }
22. }

Designing java method having more than 3 params is bad practice because of
- We must remember the order of arguments while calling method.
- Remembering lengthy method signature is very complex.

---------------
POJO class
---------------
- Plain old java object.
- The ordinary java class that is not extending or implementing technologies,
framework APIs class or interfaces is called POJO class.
- POJO class need not follow java bean standards.
- POJO class can have business methods and complex business logics.
- All java bean is POJO class but ALL POJO class is not Java bean.
Chapter-01
Spring Core
Note POJO class is not against of inheritances and implements of interfaces. It is
against of extending or implementing Technologies, framework APIs class and
interfaces

-----------------------------------------
POJI (Plain Old Java Interface)
-----------------------------------------
- The Interface that is not extending from technologies, framework APIs interface is
called POJI.
- The ordinary interface that can be compiled only using jdk libraries is called POJI.

------------------------------------------
Bean class or component class
------------------------------------------
- The java class that is having state (member variables) and behavior (methods) and
state is used inside the behavior and having reusability is called Bean class or
component class.
- The methods of component/bean class contain business logic and having
reusability.
- The component/bean class can be developed as POJO or not POJO class
- The component/bean class cannot be developed as Java Bean.
- In real projects service class (contain business logics), DAO class (persistence
Logic), controller class (monitoring logic) are component/bean class.

-------------------------------------------------
Java Bean VS Bean/component class
-------------------------------------------------
- Java bean class is different from Bean/component class
- Java bean is helper class, acting as data carrier. Component/Bean class is a main
class having main logics like business logics, persistence logics …etc.
- If we needed, we can use Java bean as data carriers between two
component/Bean classes.
Chapter-01
Spring Core
==============
Spring Container
==============
- A container is a s/w program or application that takes care of whole life cycle
(object creation to object destroy) of give resources/class.

- If a class is given to the container, the container takes care of whole life cycle of
given class by performing below operations –
I. Find/scan classes/loading class
II. Create object
III. Managing object (provide data and link objects)
IV. Destroy the object (if needed)

Example:
 Servlet container takes care of servlet classes life cycle.
 JSP container takes care of JSP files life cycle.
 Spring container/IoC container takes care of Spring beans (Classes) life cycle.

Q) Why the Spring container is called IoC container?

- Inversion of Control is a principle in software engineering, which transfers the


control of objects of a program to a container or framework.
- In core java Application development, the work of creating object will be done by
programmer using new operator i.e. programmers are the responsible to creating
objects and managing these objects.
- But in spring framework application development, the object creation and
managing process will be takes care by spring containers and making java classes
as spring beans i.e. the work of programmers is done by spring containers. So,
spring container is inversing the work of programmers by taking of their job. So,
Spring Containers are also called IoC containers.

Inversion of Control (IoC):


- By taking the control from programmer work to creating the object and managing
the life cycle of object.

Real Life Example:


Chapter-01
Spring Core
- ATM machine is doing IoC work for bank employee, because giving money and
collecting money to/from customer take care by ATM machine.

Spring Framework is giving two types of Spring container/ IoC container


1. BeanFactory(I) old
2. ApplicationContext(I) new
I. ClassPathXmlApplicationContext (C)
II. FileSystemXmlApplicationContext (C)
III. AnnotationConfigApplicationContext (C)

------------------------
Spring Bean class
------------------------
- The java class whose object is created and managed by Spring container is called
Spring bean class i.e. the whole life cycle of spring bean class will take care by
Spring container.

- Spring Bean Class follow some standards that provide Spring container -
 Class should be public
 Spring Beans can implement java.io.Serializable (I)
 Class should be in a package.
 Variables recommended to be private. Methods need to be public only.
 Provide default constructor
 For every variable provide getter and setter methods or Parameterized
constructor
 Our class can have Object class methods overridden. toString( ), equals()
and hashCode().
 Class can inherit (extends / implements) other valid Spring Beans only. But
not Servlets/EJB ...like technologies (other external APIS)

- Spring bean can be a User-define class, pre-defined class or third party supplied
class whose object is created and managed by Spring container.
Note: We cannot take abstract class or interface as a spring bean because object
creation is not possible.
Chapter-01
Spring Core
---------------------------------
Java Bean configuration
---------------------------------
- To make java class as spring bean, we need to give some Instruction to IoC
container about that java class. This is called Spring bean Configuration.
To make java class as spring bean we can configure our class in three ways
1. XML configuration
2. Annotation based configuration
3. Java Based configuration
`
========================
Dependency Management
========================

- The process of giving dependent class object to target class object is called
dependency management.
Target class: The class that usages other class services
Dependent class: The class that is used by other classes.

Where, Vehicle is a Target class which is usage Engine class services and Engine is
dependent class.
Note: Generally, we keep target and Dependent classes in HAS-A relation.
Dependency Management having two modes
1. Dependency Lookup
2. Dependency injection
Chapter-01
Spring Core
-----------------------------
Dependency Look Up
-----------------------------
- The target class contains some logic to search and get dependent class object
from different resources.
- Searching and getting object from different places in technically called lookup
operation.
Def: The dependency lookup is an approach where we get the resource after demand.
Example: The way student gets some information from google by searching for it.
-----------------
Advantages:
-----------------
- The target class gets only the required dependent class objects from different
places.
-------------------
Disadvantage:
-------------------
- The target class should explicitly write logics for what this class want to search.

====================
Dependency Injection
====================

- Dependency Injection is the concept of an object to supply dependencies of


another object by container.
- The underlying container/framework dynamically assigns/injects the dependent
class object to target class object.
Example: The moment object is created, the jvm dynamically assigns/injects default or
initial values to the objects.

-----------------
Advantages:
-----------------
- The injection process will be taken care by the container/framework. So no extra
work for target class developer.
---------------------
Disadvantages:
---------------------
- The container/framework may inject both necessary and unnecessary objects to
target class.
Chapter-01
Spring Core
The Spring IoC containers are given for two Operations
1. Spring bean life cycle Management
2. Dependency Management

-----------------
Dependency
-----------------
- A variable (Instance variable) exists inside a class (Spring bean).

There are 3 types of Dependencies in Spring framework


1. Primitive type dependency (PTD)
 byte, short, int, long, float, double, boolean, char and String If a variable is
created using one of above datatype, then it is called as PTD.
2. Collection Type Dependency
 If a variable is created using one of below types List, Set, Map [I] and
Properties (C) then it is called as CTD.
3. Reference Type Dependency (RTD)
 A class or interface is used as a DataType and variable is created then it is
called as RTD.
------------
Injection
------------
- Providing data to the variable (after object creation)

Type of Dependency Injections


1. Setter Injection (SI):
- Provide/inject value to dependency using setter/set method. Object is
created using default constructor and data is provided using set method.

Example:
1. class A{
2. int id;
3. void setId(int id) {
4. this.id = id;
5. }
6. }
7. A oa = new A();
8. oa.setId(10);
Chapter-01
Spring Core
2. Constructor Injection (CI):
- Creating object and providing data using parameterized constructor.
Example:
1. class A{
2. int id;
3. A(int id) {
4. this.id = id;
5. }
6. }
7. A oa = new A(10);

3. Field Injection
4. Interface Injection
5. Lookup method Injection

We can develop Spring apps in 3 Approachs


1. Using XML configuration
- All instruction to Spring IoC will be given through XML file
2. XML + annotation configuration
- All instruction to Spring IoC will be given through XML file + Annotations
3. Java configuration + annotation

-----------------------------------------------------------
Spring Application Using XML configuration
-----------------------------------------------------------

XML configuration Tags


1. <bean> --------------- for creating object
2. <property> --------------- for setter injection
3. <constructor-arg> --------------- for constructor injection (using param constructor
 <value> --------------- for primitive value
 <list>, <set>, <map> <props> ----- for collection
 <ref> ------------- for reference type
Chapter-01
Spring Core
----------------------------------------------------------------
Step to Spring Application using setter injection
----------------------------------------------------------------
1. Create simple maven project
2. Add dependency in pom.xml file
 Maven compiler plugin
 Spring context maven Dependency
1. <properties>
2. <maven.compiler.source>1.8</maven.compiler.source>
3. <maven.compiler.target>1.8</maven.compiler.target>
4. </properties>
5. <dependencies>
6. <!--https://mvnrepository.com/artifact/org.springframework/spring-context -->
8. <dependency>
9. <groupId>org.springframework</groupId>
10. <artifactId>spring-context</artifactId>
11. <version>5.3.22</version>
12. </dependency>

3. Create MyApp class followed by Spring bean rules in src/main/java


1. package org.nadim.bean;
2.
3. public class MyApp {
4.
5. private String empName;
6. public String getName() {
7. return empName;
8. }
9. public void setEmpName(String empName) {
10. this. empName = empName;
11. }
12. public MyApp() {
13. super();
14. }
15. @Override
16. public String toString() {
17. return "MyApp [name=" + empName + "]";
18. }
19. }

4. Create xml file into src/main/resource with name “ApplicationContext.xml”


recommended and set “Spring XML configuration”
1. <bean id="myapp" class="org.nadim.bean.MyApp">
2. <property name="empName">
3. <value>Nadim</value>
4. </property>
5. </bean>
Chapter-01
Spring Core
5. Create Spring Container and read data
1. public class MyAppContainer {
2.
3. public static void main(String[] args) {
4.
5. ApplicationContext context
6. = new ClassPathXmlApplicationContext("ApplicationContext.xml");
7. MyApp app = (MyApp)context.getBean("myapp");
8. System.out.println(app);
9. }
10. }

------------------------------------------------------------------------
Step to Spring Application using Constructor injection
------------------------------------------------------------------------
Creation of new Application is same process
1. Create MyApp class followed by Spring bean rules in src/main/java
1. public class SecondApp {
2. Integer roll;
3. String name;
4. // default constructor
5. SecondApp() {
6.
7. }
8. // Parameterized constructor
9. SecondApp(Integer roll, String name) {
10. this.roll = roll;
11. this.name=name;
12. }
13.
14. @Override
15. public String toString() {
16. return "SecondApp [roll=" + roll + ", name=" + name + "]";
17. }
18. }
Chapter-01
Spring Core
2. Create xml file into src/main/resource with name “ApplicationContext.xml”
recommended and set “Spring XML configuration”
1. <bean id="obj" class="com.nadim.SecondApp">
2. <constructor-arg name="roll">
3. <value>15</value>
4. </constructor-arg>
5. <constructor-arg name="name">
6. <value>Nadim Mostafa</value>
7. </constructor-arg>
8. </bean>

3. Create Spring Container and read data


1. public class Main {
2. public static void main(String[] args) {
3. ApplicationContext cxt = new
ClassPathXmlApplicationContext("config.xml");
4.
5. SecondApp obj = (SecondApp) cxt.getBean("obj");
6. System.out.println(obj);
7. }
8. }

--------------------------------------------------------------------
Spring Application Using Annotation configuration
--------------------------------------------------------------------
- No lengthy configuration
- Annotation Configuration is faster compared to XML because no reading /
parsing for additional files.
- Annotation Configuration can be used only for user define classes (if we
have .java code, can be compiled)
- Annotation Configuration is used for default single object for a class.
- For Annotation configuration we need
AnnotationConfigApplicationContext class to start Spring container.

Stereo type annotation:


- An annotation that informs spring container to create the object

There are five Stereo type annotation


Chapter-01
Spring Core
1. @Component
 Used to config java class as the spring bean to container and create object
to that class.
2. @Service
 This annotation informs spring container to create and object and enable
transaction management and business logic.
3. @Controller
 This annotation used in web MVC and create an object and support http
operations.
4. @Repository
 Used to Create object and indicates that the class provides the Database
operations.
5. @RestController
 It is used to create an object, support http operations and create RESTful
web services. This annotation is combination of @Controller +
@ResponseBody

@Value
 It is called as value-based Injection/Direct Injection/field injection that is, to
provide data to variable (not need to setter method and parameterized
constructor only need no-arg constructor).
 We can use in 3 different 3 use cases
I. To inject hardcode value to variables / dependencies
Example:
@Value(“Nadim”)
String name;
II. To read data from resources ( .properties/.yml/.xml)
III. To provide one SpEL (Spring Expression Language)

==========
Coding step
==========

1. Create simple maven project


2. Add dependency in pom.xml file
 Maven compiler plugin
 Spring context maven Dependency
Chapter-01
Spring Core
3. Create MyApp class followed by Spring bean rules in src/main/java and Add
“@Component” annotation on top of the class.
1. package org.example;
2. @Component("myApp")
3. public class MyApp {
4. @Value("Nadim")
5. private String name;
6. @Value("27")
7. private Integer age;
8.
9. public MyApp() {
10. }
11. @Override
12. public String toString() {
13. return "MyApp{" +
14. "name='" + name + '\'' +
15. ", age=" + age +
16. '}';
17. }
18. }

4. Create Spring Container and read data

1. public class Main {


2. public static void main(String[] args) {
3. AnnotationConfigApplicationContext ac
4. = new AnnotationConfigApplicationContext();
5. ac.scan("org.example");
6. ac.refresh();
7. MyApp app = ac.getBean("myApp",MyApp.class);
8. System.out.println(app);
9. }
10. }

Here,
scan(“basePackage”)
 Fild all Spring bean class from given BasePackage or its sub-packages
refresh()
 Re-fresh spring container/ re-initialization of container

In real-time project those are not use, instead of we use @ComponentScan annotation
Chapter-01
Spring Core
@ComponentScan
 It is the process of scanning the spring bean class available in the given base
package or its sub-package.

 If class having @Component then container will create the object. It is used only
for annotation configuration.

 @ComponentScan(basePackages = "com.app") means find classes from com.app


package and com.app all subpackage classes.

 Define one additional class to provide basePackage using annotation


@ComponentScan and Provide that class as a constructor argument to the
AnnotationConfigApplicationContext() class.

BasePackage
 This is the input must be given in-case of Spring Annotation configuration (So that
container can find our classes based on BasePackage)

==========
Coding Step
==========
1. Create simple maven project
2. Add dependency in pom.xml file
 Maven compiler plugin
 Spring context maven Dependency

3. Create MyApp class followed by Spring bean rules in src/main/java and Add
“@Component” annotation on top of the class.
1. package org.example;
2. @Component("myApp")
3. public class MyApp {
4. @Value("Nadim")
5. private String name;
6. @Value("27")
7. private Integer age;
8.
9. public MyApp() {
10. }
11. @Override
12. public String toString() {
13. return "MyApp{" +
14. "name='" + name + '\'' +
15. ", age=" + age +
16. '}';
17. }
Chapter-01
Spring Core
18. }

4. Define one additional class to provide base Package using annotation


@ComponentScan.
1. @ComponentScan("org.example")
2. public class MyConfigApp {
3. }

5. Create Spring Container and read data


1. public class Main {
2. public static void main(String[] args) {
3. AnnotationConfigApplicationContext ac =
4. new AnnotationConfigApplicationContext(MyConfigApp.class);
5. EmailApp eapp=(EmailApp) ac.getBean("email");
6. System.out.println(eapp);
7. }
8. }

======================================
Read data from .properties file using @Value
======================================

---------------------
.properties file
---------------------
- To start application Some data is required like Database Connection, JPA
(Hibernate) Details, Email Config, Security Configuration… etc. such type of data
we have to configure in. properties file
- In our application if anything which is change frequently (like username,
password, database properties … etc. are not recommended to hardcode directly
in our application. Such type of data we have to configure in. properties.

In src/main/resources directory we can define _____.properties file using below rules-


- File name like myapp.properties
- .properties file will store data in key=val format where key are case-sensitive.
- If same key is provided multiple time with different value, then last combination is
taken.
- Symbol # indicates comment in properties file. You can use _(underscore) . (dot) -
(dash) symbols in key name.
- Auto parsing is supported based on variable datatype. By default, key and value
(both) are String datatype.
Chapter-01
Spring Core
To load .properties into Spring container using annotation @PrpertySource(classpath:
filename.properties).
-------------------------
@PropertySource:
-------------------------
- To load data into spring container from .properties file and spring container
create an Environment memory to hold .properties key-value data.
- Environment(I) interface and its implementation class StandardEnvironment

Example:
@PropertySource(“classpath:MyApp.properties”)
Where, Classpath – Indicates {src/main/resources} directory

Q) How to read data from .properties file using Environment memory?

- Using @Value annotation on top of the variable


- Syntex: @Value(“${nameOfKey}”)
==========
Coding Step
==========

1. Create simple maven project


2. Add dependency in pom.xml file
 Maven compiler plugin
 Spring context maven Dependency

3. Create MyApp class followed by Spring bean rules in src/main/java and Add
“@Component” annotation on top of the class.
1. package org.example;
2.
3. @Component("con")
4. public class MyDBConnection {
5. @Value("${my-driver}")
6. private String driver;
7. @Value("${my-url}")
8. private String url;
9.
10. public MyDBConnection() {
11. }
12.
13. @Override
14. public String toString() {
15. return "MyDBConnection{" + "driver='" + driver + '\'' +
16. ", url='" + url + '\'' +'}';
17. }
Chapter-01
Spring Core
4. Create config.properties file in src/main/resources file
1. # command using #
2. my-dirver = oracle.jdbc.OracleDriver
3. my-url = jdbc:orcale:thin:@localhost1521:orcl
5. Define one additional class as a configuration class
1. //@PropertySource("config.properties") or
2. @PropertySource("classpath:config.properties")
3. @ComponentScan(basePackages = "org.example")
4. public class MyConfigApp {
5. }

6. Create Spring Container and read data


1. public class Main {
2. public static void main(String[] args) {
3. AnnotationConfigApplicationContext ac =
4. new AnnotationConfigApplicationContext(MyConfigApp.class);
5. MyDBConnection con = ac.getBean("con",MyDBConnection.class);
6. System.out.println(con);
7. }

Dependency Injection is also called as Bean wiring.

Two types of Bean Wiring


-----------------------------------

1. Explicit wiring
- We need to <property> or <construct-arg> tags in xml explicitly for
dependency injection.
2. Auto wiring or Implicit wiring
- We do not use <property> or <construct-arg> tags. We make IOC container
to detect the dependent spring beans dynamically and inject to target
spring bean class objects based on type or name of properties.
- To enable auto wiring in xml cfgs use “autowire” attribute in <bean> tag or
in annotation based cfgs we use @Autowired annotation.

===========
@Autowired
===========
- Autowiring feature of spring framework enables you to inject the object
dependency implicitly.
- Injecting Dependency object into dependent class automatically by spring
container.
Chapter-01
Spring Core
- Autowiring can't be used to inject primitive and string values. It works with
reference only.
- @Autowired annotation can be applied at field level, method level of
constructor level.
Example:

@Autowired 3 case analysis

Case-01:
- If child object is found then link them/ inject object

Case-02:
- If find zero dependency object or unable to find dependency object then
we will get exception: NoSuchBeanDefFoundException.

Example:

- In this case if we want to avoid exception then we will set manually


@Autowired(required=false). For this case if dependency bean is not
present then object value is null.
- By default, @Autowired(required=true)

Example:
Chapter-01
Spring Core

Case-03:
- If child class multiple objects will found then container throws exception:
NoUniqueBeanDefinitionException.

Pending……..

=====================
Spring Life cycle methods
=====================

Lifecycle Method:
- A method which is called by container/ f/w. /VMs in between Object
creation and destroy.

Adv Java (Servlets) --- 3 Lifecycle Methods (Must be there)


1. init()
2. service()
3. destroy()

In spring container 2 lifecycle methods


1. init()
2. destroy()
- Note: it will be executed before destroy the object. destroy() method
never destroy the objects.

 These lifecycle methods are used to connect with external resources that is
used in our program.
 These methods are optional
 Lifecycle methods never called manually. These are called by container,
framework etc.
Chapter-01
Spring Core
Spring Lifecycle Method execution flow:
1. Find/scan Spring bean class
2. Create object (Constructor execution)
3. Inject dependencies (Setter method execution)
4. Inti() lifecycle method execution
5. Used/read object by programmer (ac.getBean())
6. destroy() method execution – if we want to show the destroy method then
create Spring container CPXA ac = new CPXA(_________.xml) then class
ac.close() then show the destroy method execution.
7. destroy the object/container

We can define life cycle method in 3 way


1. Using XML configuration
- In bean tags we need to define to attribute
o Init-method= “methodName”
o Destroy-method= “methodName”
Example:
1. <bean id="dbcon" class="org.example.Repository" init-method="startUp" destroy-method="cleanUp">
3. </bean>

2. Using pre-define Interfaces


- InitializingBean(I) and override method afterPropertySet()
DisposableBean(I) and override method destroy()

3. Annotation Configuration (JSR annotation)


- @PostConstructor
- @PreDestroy

Note: For annotation configuration we need to add one dependency (JSR 250 maven
dependency) is required.

1. <dependency>
2. <groupId>javax.annotation</groupId>
3. <artifactId>javax.annotation-api</artifactId>
4. <version>1.3.2</version>
5. </dependency>
Chapter-01
Spring Core

Q) What is the difference between IoC and Dependency Injection?


- IoC is specification providing rules and guidelines to manage dependency
between target and dependent classes.
- Dependency Lookup and Dependency Injection are two implementation models
of IoC

Q) Which class is called Spring bean?


- Which java class is loaded, objected, object managed by Spring container and
follow some rules those are given by Spring Container is called Spring bean.
Q) Why Spring container is called light weight container?
- Servlet container, JSP container and EJB container…etc. are the heavy weight
containers because to start/active them we need to install and start the other
heavy weight webserver s/w (tomcat) or application s/w (glassfish) which uses
the more CPU time (processing time) and more memory (RAM memory required
for execution).
- But Spring IoC containers are light weight because they can be in any code/app by
just creating the object for pre-define class of spring API.
- To Create BeabFactory container, create the object for java class that implements
BeanFactory(I).
Example: XmlBeanFactory class implements BeanFactory(I). By creating
XmlBeanFactory class object we can create Spring Container.
- Spring containers are light weight because, without installing any web-server or
any application server by just creating the object for java class then spring
container is ready.
Chapter-01
Spring Core

You might also like