Spring Core
Spring Core
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.
------------------------
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
====================
-----------------
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).
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
-----------------------------------------------------------
Spring Application Using XML configuration
-----------------------------------------------------------
------------------------------------------------------------------------
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>
--------------------------------------------------------------------
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.
@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
==========
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.
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. }
======================================
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.
Example:
@PropertySource(“classpath:MyApp.properties”)
Where, Classpath – Indicates {src/main/resources} directory
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. }
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:
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:
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.
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
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