SlideShare a Scribd company logo
Spring Basics
annotation based
application development
https://github.com
/Innominds-jee
/spring-java-training.git
Index
 Introduction
 Spring Containers
 Spring Bean Lifecycle
 Spring Annotations
 Spring Bean Scopes
 Profiles & Conditional Beans
 Spring AOP
 Spring Expression Language (SpEL)
Introduction
 Spring started as a lightweight alternative to Java
Enterprise Edition. (Using EJBs)
 Spring offered a simpler approach to enterprise
Java development, utilizing dependency injection
and aspect-oriented programming to achieve the
capabilities of EJB with plain old Java objects
(POJOs).
 Spring 2.5 introduced annotation-based
component-scanning, which eliminated a great
deal of explicit XML configuration for an
application’s own components. And Spring 3.0
introduced a Java-based configuration as a type-
safe and refactorable option to XML.
Spring Basics
Spring as an integration framework
Spring has support in different areas
Web Layer: we can integrate with HTML,JSP,
thymeleaf, velocity, freemarker, tiles etc.
Scripting : groovy, JRuby, BeanShell
Messaging: supports ActiveMQ, RabbitMQ
Security Method level and Http URLs
ORM : hibernate, eclipselink with JPA
NoSQL: supports MongoDB, elastic search
Popular frameworks are also dependent on
spring. Ex: Hybris, Mule ESB, Liferay, Magnolia
IoC Introduction (from spring docs)
 IoC is also known as dependency injection (DI).
 It is a process whereby objects define their
dependencies, that is, the other objects they work
with, only through constructor arguments, arguments
to a factory method, or properties that are set on the
object instance after it is constructed or returned from
a factory method.
 The container then injects those dependencies when
it creates the bean.
 This process is fundamentally the inverse, hence the
name Inversion of Control (IoC)
Types of Containers
There are two types of containers
 BeanFactory Container: This is the simplest
container providing basic support for DI.
It creates beans on demand.
 ApplicationContext Container: This container
adds more enterprise-specific functionality such
as the ability to resolve textual messages from a
properties file and the ability to publish application
events to interested event listeners. It creates
beans upon starting the application.
Spring container hierarchy
Spring web application containers hierarchy
Spring bean lifecycle
Java based configuration
Java based spring container can be created
using below class
final AnnotationConfigApplicationContext aCtx
= new AnnotationConfigApplicationContext();
aCtx.register(MySpringConfig.class); //pass the configuration
aCtx.refresh();// it will creates the registered beans
Spring Annotation
 @Configuration: Configuration file
 @Bean: to declare a bean in Java configuration
 @Import : import another Java Configuration
 @ImportResource : import XML configuration
 @ComponentScan: scans the beans starting with given base
package
 @Scope: to define Scope of a bean
 @Conditional: this works with Condition interface
 @EnableAspectJAutoProxy: enabling auto proxy, @Aspect
 @Primary: works with @Component
 @Qualifier: works with @Autowired and @Inject
 @Value: annotation spring express Language
 @ActiveProfiles: choose profiles in Test cases
 @ContextConfiguration: To load with configuration test cases
 @Runwith: Runwith(SpringJUnit4ClassRunner)
Basic Annotations in Spring
 @Configuration: Indicates that a class declares
one or more @Bean methods and may be processed
by the Spring container to generate bean definitions
and service requests for those beans at runtime
 @Bean: Creates Spring bean from java object
 @Import: Used to import configuration file
 @ImportResource: Used to import XML
Based Configuration file
 ComponentScan: scans the spring beans on
the given base package. It looks for
@Service, @Component, @Controller,
@Repository .
Spring Bean Scopes
 Singleton: Single bean per IOC container (default)
 Prototype: creates new bean each time
WEB APPLICATION SCOPES
 Request: each request new bean created
 Session: for each user session new bean created
 Global Session: Typically only valid when used in a
portlet context.
NOTE: you can also create your own scope if these are not fit to
your requirement
There are two types of scope available in spring core
container
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
Enabling profile
 Spring Profiles were introduced in spring 3.1.
It allows us to define beans by deployment regions such as
“dev” , “qa”, “prod” etc.
 Spring profiles are enabled using the case insensitive tokens
spring.profiles.active or spring_profiles_active.
 Profile can be activated with below mentioned ways
1. an Environment Variable
2. a JVM Property
3. Web Parameter
4. Programmatic
@Profile Annotation used to create bean for specific environment
Conditional Beans
Conditional Beans were introduced in spring 4.0
It works together with @Conditional annotation and Condition
interface
It allows developer to define strategy to create bean. These are not
limited to environment
Spring boot framework extensively uses this feature to create bean
based on properties file information
@Bean
@Conditional(LinuxMailConditon.class)
MailService mailService() {
return new LinuxMailServiceImpl();
}
@Bean
@Conditional(WindowsMailConditon.class)
MailService mailService() {
return new WindowsMailServiceImpl();
}
JDBC Template condition
public class JdbcTemplateCondition implements Condition {
@Override
public boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata) {
try {
context.getClassLoader().loadClass("org.springframework.jdbc
. core.JdbcTemplate");
return true;
} catch (Exception e) {
return false;
}
}
}
Aspect Oriented Programming
 Cross-cutting Concerns impact the application
in many points. Ex: Logging, Security, Caching
and Transaction Management are called cross-
cutting concerns.
 Using AOP we can define common functionality in
one place and we can declaratively define how
and where this functionality can be applied.
 Cross cutting concerns are modularized into
special classes are called aspects.
AOP Terminology
 Aspect: modularization of cross-cutting concern
ex: security Aspect will check whether calling person has privileges to
access checkBalance() method
 Advice: Job of an Aspect called advice.
 Joinpoints: In an application there are many places
where we can apply aspect. These points are called
join points.
 Pointcuts: point cuts are the join points where we can
woven advice.
 Introductions: inject new methods and attributes into
existing classes are called introductions.
 Weaving: process of applying aspects to target
classes to create new proxies.
Types of Weaving
 Compile time Weaving: Aspects are woven when
the target class is compiled. It requires special
kind of compiler. (works only on AspectJ
programming model).
 Classloading time: Aspects are weaving when
the class loaded by the class loader. This kind of
weaving requires special kind of classLoader.
(works only with AspectJ )
 Runtime weaving: Aspects are woven during the
runtime of the program execution. AOP container
dynamically generates proxy objects that delegate
the requests to target objects. (Spring AOP
supports only this)
Types of Advice
 @Before
 @After
 @AfterReturning
 @AfterThrowing
 @Around
Configuring AOP in spring project
 It is just adding below annotations to configuration file
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true)
 And Writing some pointcuts and advice annotations
@Before("execution(** com.innominds.aop.service.*.*())")
public void beforeMethod() {
//write JOB of aspect
}
NOTE: Spring doesn’t provide its own annotations instead
it depends on AspectJ annotations.
 In Spring, aspects are woven into spring-
managed beans at runtime by wrapping them
with a proxy class.
There are two types of proxy creation possible
 JDK Dynamic proxy: If the services are invokes
based on interfaces it creates proxy by
implementing that interface.
 CGLIB Proxy: it extends the existing target class
and calls super class methods.
 Proxy class poses as the target bean intercepting
advised method calls and forwarding those calls
to the target bean.
How JDK Proxy works
Spring Expression Language with @Value
annotation
 A powerful expression language that supports
querying and manipulating an object graph at
runtime.
 syntax to define the expression is of the form
#{ <expression string> }.
 @Value annotation used to bound the value
from the spring expression language.
@Primary and @Qualifier
 @Primary: used to select one default
implementation when multiple concrete classes
available for single interface.
 @Qualifier: Used to select one of the
implementation at the time of @Autowiring
Spring Testing
 @Runwith : Used to select spring test runner with
Junit Test cases
 @ContextConfiguration: take spring
configuration and creates container with test
beans
 @ActiveProfiles: enables profiles form test
cases
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PaymentConfig.class })
@ActiveProfiles(profiles = { "dev" })
public class PaymentServiceTest {}
Ad

More Related Content

What's hot (20)

Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
Hùng Nguyễn Huy
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
Aaron Schram
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02
Guo Albert
 
Building web applications with Java & Spring
Building web applications with Java & SpringBuilding web applications with Java & Spring
Building web applications with Java & Spring
David Kiss
 
Spring tutorial
Spring tutorialSpring tutorial
Spring tutorial
Sanjoy Kumer Deb
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Spring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 IntegrationSpring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 Integration
Majurageerthan Arumugathasan
 
Introduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring MvcIntroduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring Mvc
Abdelmonaim Remani
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
Mohit Gupta
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
zeeshanhanif
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
Eleonora Ciceri
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
Emprovise
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
Harshit Choudhary
 
Servlets lecture1
Servlets lecture1Servlets lecture1
Servlets lecture1
Tata Consultancy Services
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
Ravi Kant Soni ([email protected])
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
Spring Core
Spring CoreSpring Core
Spring Core
Pushan Bhattacharya
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
Guo Albert
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02
Guo Albert
 
Building web applications with Java & Spring
Building web applications with Java & SpringBuilding web applications with Java & Spring
Building web applications with Java & Spring
David Kiss
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Introduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring MvcIntroduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring Mvc
Abdelmonaim Remani
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
Mohit Gupta
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
Guo Albert
 

Similar to Spring Basics (20)

Java spring ppt
Java spring pptJava spring ppt
Java spring ppt
natashasweety7
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
Mindsmapped Consulting
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2
javatrainingonline
 
Spring framework
Spring frameworkSpring framework
Spring framework
Rajkumar Singh
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
Aneega
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Dineesha Suraweera
 
Spring framework
Spring frameworkSpring framework
Spring framework
vietduc17
 
Signal Framework
Signal FrameworkSignal Framework
Signal Framework
Aurora Softworks
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Z
sang nguyen
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
NexThoughts Technologies
 
Spring framework
Spring frameworkSpring framework
Spring framework
Sonal Poddar
 
Introduction to Spring sec1.pptx
Introduction to Spring sec1.pptxIntroduction to Spring sec1.pptx
Introduction to Spring sec1.pptx
NourhanTarek23
 
Spring notes
Spring notesSpring notes
Spring notes
Rajeev Uppala
 
Spring framework Introduction
Spring framework IntroductionSpring framework Introduction
Spring framework Introduction
Anuj Singh Rajput
 
spring framework ppt by Rohit malav
spring framework ppt by Rohit malavspring framework ppt by Rohit malav
spring framework ppt by Rohit malav
Rohit malav
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
AnushaNaidu
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
Mehul Jariwala
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorial
vinayiqbusiness
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
Rajiv Gupta
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
Muthuselvam RS
 
Ad

Recently uploaded (20)

How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Ad

Spring Basics

  • 1. Spring Basics annotation based application development https://github.com /Innominds-jee /spring-java-training.git
  • 2. Index  Introduction  Spring Containers  Spring Bean Lifecycle  Spring Annotations  Spring Bean Scopes  Profiles & Conditional Beans  Spring AOP  Spring Expression Language (SpEL)
  • 3. Introduction  Spring started as a lightweight alternative to Java Enterprise Edition. (Using EJBs)  Spring offered a simpler approach to enterprise Java development, utilizing dependency injection and aspect-oriented programming to achieve the capabilities of EJB with plain old Java objects (POJOs).  Spring 2.5 introduced annotation-based component-scanning, which eliminated a great deal of explicit XML configuration for an application’s own components. And Spring 3.0 introduced a Java-based configuration as a type- safe and refactorable option to XML.
  • 5. Spring as an integration framework Spring has support in different areas Web Layer: we can integrate with HTML,JSP, thymeleaf, velocity, freemarker, tiles etc. Scripting : groovy, JRuby, BeanShell Messaging: supports ActiveMQ, RabbitMQ Security Method level and Http URLs ORM : hibernate, eclipselink with JPA NoSQL: supports MongoDB, elastic search Popular frameworks are also dependent on spring. Ex: Hybris, Mule ESB, Liferay, Magnolia
  • 6. IoC Introduction (from spring docs)  IoC is also known as dependency injection (DI).  It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.  The container then injects those dependencies when it creates the bean.  This process is fundamentally the inverse, hence the name Inversion of Control (IoC)
  • 7. Types of Containers There are two types of containers  BeanFactory Container: This is the simplest container providing basic support for DI. It creates beans on demand.  ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. It creates beans upon starting the application.
  • 9. Spring web application containers hierarchy
  • 11. Java based configuration Java based spring container can be created using below class final AnnotationConfigApplicationContext aCtx = new AnnotationConfigApplicationContext(); aCtx.register(MySpringConfig.class); //pass the configuration aCtx.refresh();// it will creates the registered beans
  • 12. Spring Annotation  @Configuration: Configuration file  @Bean: to declare a bean in Java configuration  @Import : import another Java Configuration  @ImportResource : import XML configuration  @ComponentScan: scans the beans starting with given base package  @Scope: to define Scope of a bean  @Conditional: this works with Condition interface  @EnableAspectJAutoProxy: enabling auto proxy, @Aspect  @Primary: works with @Component  @Qualifier: works with @Autowired and @Inject  @Value: annotation spring express Language  @ActiveProfiles: choose profiles in Test cases  @ContextConfiguration: To load with configuration test cases  @Runwith: Runwith(SpringJUnit4ClassRunner)
  • 13. Basic Annotations in Spring  @Configuration: Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime  @Bean: Creates Spring bean from java object  @Import: Used to import configuration file  @ImportResource: Used to import XML Based Configuration file  ComponentScan: scans the spring beans on the given base package. It looks for @Service, @Component, @Controller, @Repository .
  • 14. Spring Bean Scopes  Singleton: Single bean per IOC container (default)  Prototype: creates new bean each time WEB APPLICATION SCOPES  Request: each request new bean created  Session: for each user session new bean created  Global Session: Typically only valid when used in a portlet context. NOTE: you can also create your own scope if these are not fit to your requirement There are two types of scope available in spring core container @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  • 15. Enabling profile  Spring Profiles were introduced in spring 3.1. It allows us to define beans by deployment regions such as “dev” , “qa”, “prod” etc.  Spring profiles are enabled using the case insensitive tokens spring.profiles.active or spring_profiles_active.  Profile can be activated with below mentioned ways 1. an Environment Variable 2. a JVM Property 3. Web Parameter 4. Programmatic @Profile Annotation used to create bean for specific environment
  • 16. Conditional Beans Conditional Beans were introduced in spring 4.0 It works together with @Conditional annotation and Condition interface It allows developer to define strategy to create bean. These are not limited to environment Spring boot framework extensively uses this feature to create bean based on properties file information @Bean @Conditional(LinuxMailConditon.class) MailService mailService() { return new LinuxMailServiceImpl(); } @Bean @Conditional(WindowsMailConditon.class) MailService mailService() { return new WindowsMailServiceImpl(); }
  • 17. JDBC Template condition public class JdbcTemplateCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { try { context.getClassLoader().loadClass("org.springframework.jdbc . core.JdbcTemplate"); return true; } catch (Exception e) { return false; } } }
  • 18. Aspect Oriented Programming  Cross-cutting Concerns impact the application in many points. Ex: Logging, Security, Caching and Transaction Management are called cross- cutting concerns.  Using AOP we can define common functionality in one place and we can declaratively define how and where this functionality can be applied.  Cross cutting concerns are modularized into special classes are called aspects.
  • 19. AOP Terminology  Aspect: modularization of cross-cutting concern ex: security Aspect will check whether calling person has privileges to access checkBalance() method  Advice: Job of an Aspect called advice.  Joinpoints: In an application there are many places where we can apply aspect. These points are called join points.  Pointcuts: point cuts are the join points where we can woven advice.  Introductions: inject new methods and attributes into existing classes are called introductions.  Weaving: process of applying aspects to target classes to create new proxies.
  • 20. Types of Weaving  Compile time Weaving: Aspects are woven when the target class is compiled. It requires special kind of compiler. (works only on AspectJ programming model).  Classloading time: Aspects are weaving when the class loaded by the class loader. This kind of weaving requires special kind of classLoader. (works only with AspectJ )  Runtime weaving: Aspects are woven during the runtime of the program execution. AOP container dynamically generates proxy objects that delegate the requests to target objects. (Spring AOP supports only this)
  • 21. Types of Advice  @Before  @After  @AfterReturning  @AfterThrowing  @Around
  • 22. Configuring AOP in spring project  It is just adding below annotations to configuration file @Aspect @EnableAspectJAutoProxy(proxyTargetClass = true)  And Writing some pointcuts and advice annotations @Before("execution(** com.innominds.aop.service.*.*())") public void beforeMethod() { //write JOB of aspect } NOTE: Spring doesn’t provide its own annotations instead it depends on AspectJ annotations.
  • 23.  In Spring, aspects are woven into spring- managed beans at runtime by wrapping them with a proxy class. There are two types of proxy creation possible  JDK Dynamic proxy: If the services are invokes based on interfaces it creates proxy by implementing that interface.  CGLIB Proxy: it extends the existing target class and calls super class methods.  Proxy class poses as the target bean intercepting advised method calls and forwarding those calls to the target bean.
  • 24. How JDK Proxy works
  • 25. Spring Expression Language with @Value annotation  A powerful expression language that supports querying and manipulating an object graph at runtime.  syntax to define the expression is of the form #{ <expression string> }.  @Value annotation used to bound the value from the spring expression language.
  • 26. @Primary and @Qualifier  @Primary: used to select one default implementation when multiple concrete classes available for single interface.  @Qualifier: Used to select one of the implementation at the time of @Autowiring
  • 27. Spring Testing  @Runwith : Used to select spring test runner with Junit Test cases  @ContextConfiguration: take spring configuration and creates container with test beans  @ActiveProfiles: enables profiles form test cases @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PaymentConfig.class }) @ActiveProfiles(profiles = { "dev" }) public class PaymentServiceTest {}