SlideShare a Scribd company logo
1 of 27
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 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 {}

More Related Content

What's hot

Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02Guo Albert
 
Building web applications with Java & Spring
Building web applications with Java & SpringBuilding web applications with Java & Spring
Building web applications with Java & SpringDavid Kiss
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCFAKHRUN 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 topicsGuy 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 MvcAbdelmonaim Remani
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC frameworkMohit Gupta
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsKaml 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 HTML5Tuna Tore
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkGuo Albert
 

What's hot (20)

Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02
 
Building web applications with Java & Spring
Building web applications with Java & SpringBuilding web applications with Java & Spring
Building web applications with Java & Spring
 
Spring tutorial
Spring tutorialSpring tutorial
Spring tutorial
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
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
 
Spring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 IntegrationSpring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 Integration
 
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
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Servlets lecture1
Servlets lecture1Servlets lecture1
Servlets lecture1
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
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
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
 

Similar to Spring Basics

Similar to Spring Basics (20)

Java spring ppt
Java spring pptJava spring ppt
Java spring ppt
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Signal Framework
Signal FrameworkSignal Framework
Signal Framework
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Z
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Introduction to Spring sec1.pptx
Introduction to Spring sec1.pptxIntroduction to Spring sec1.pptx
Introduction to Spring sec1.pptx
 
Spring notes
Spring notesSpring notes
Spring notes
 
Spring framework Introduction
Spring framework IntroductionSpring framework Introduction
Spring framework Introduction
 
spring framework ppt by Rohit malav
spring framework ppt by Rohit malavspring framework ppt by Rohit malav
spring framework ppt by Rohit malav
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorial
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 

Recently uploaded

Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 

Recently uploaded (20)

Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 

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.
  • 4.
  • 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 {}