1.15k likes | 1.27k Views
Basics of. Spring Framework. Spring Framework. Basics Introduction to IoC and AOP Spring Core AOP in Detail Bean Lifecycle Extensibility Spring - The Beginning… References Questions/Feedback. Agenda. Spring Framework. 01 Basics. Spring Framework.
E N D
Basics of Spring Framework
Spring Framework Basics Introduction to IoC and AOP Spring Core AOP in Detail Bean Lifecycle Extensibility Spring - The Beginning… • References • Questions/Feedback Agenda
Spring Framework 01 Basics
Spring Framework Spring is a Lightweight, Inversion of Control and Aspect-Oriented Container Framework Lightweight Inversion of Control Aspect Oriented Container Framework Spring?
Spring Framework Spring Goals • Play role in Enterprise Application Architecture • Core Support • Web Application Development Support • Enterprise Application Development Support • Spring Triangle 5
Spring Framework Spring Triangle Dependency Injection Aspect Oriented Programming Enterprise Service Abstractions 6
Spring Framework To make J2EE easier to use and promote EBP Always better to program to interfaces than classes JavaBeans are a great way to configure applications Framework should not force to catch exceptions if one is unlikely to recover from them Testing is essential and framework should make it easier To make integration with existing technologies easier To easily integrate in existing projects Spring Objectives
Spring Framework Organizes middle tier objects Eliminates proliferation of singletons Spring is mostly non-intrusive* Applications built on Spring are easy to Unit Test Use of EJB becomes an implementation choice Consistent framework for Data Access whether JDBC or O/R mapping Any part of Spring can be used in isolation. Provides for flexible architecture Benefit to all application layers Spring Advantages
Spring Framework Spring Layers AOP ORM Web Web MVC DAO Context Core
Spring Framework Service Interface to which we program. Implementation Concrete class implementing the service. Wiring Act of creating associations between application components. CollaboratorsServices used by a service to perform business operations Inversion of Control AOP Lingua-Franca
Spring Framework 02 Introduction to IoC & AOP
Spring Framework public class ProductServicesImpl implements ProductServices { public List getAllProducts(String loanTerm) throws Exception { PricingServiceImpl service = new PricingServiceImpl(); return service.getAllProducts(loanTerm); } } public class ProductServicesTest extends TestCase { public void testGetAllProducts() { ProductServices service = new ProductServicesImpl(); try { List products = service.getAllProducts(“30”); assertNotNull(products); } catch (Exception e) { assertTrue(false); } } } IoC Example ProductServiceImpl new PricingServiceImpl() JNDI Lookup PricingServiceImpl
Spring Framework public class ProductServicesImpl implements ProductServices { private PricingService service; public List getAllProducts(String loanTerm, PricingService service) throws Exception { return service.getAllProducts(loanTerm); } public List getAllProducts(String loanTerm) throws Exception { return service.getAllProducts(loanTerm); } public void setPricingService(PricingService service) { this.service = service; } } IoC Example - revisited ProductServiceImpl By setter injection By constructor injection PricingServiceImpl
Spring Framework It is the acquisition of dependent objects that is being inverted. Hence, can be termed as “Dependency Injection” Applying IoC, objects are given their dependent objects at creation time (at runtime) by some external entity that coordinates with each object in the system. Inversion of Control
Spring Framework Complements OOP Decomposition of aspects/concerns Modularization of concerns that would otherwise cut across multiple objects Reduces duplicate code Usages • Logging • Persistence • Transaction Management • Debugging • Performance Metrics Aspect Oriented Programming
Spring Framework Cross Cutting Concerns Transaction Management Security Logging/Exception Handling Performance Metrics Auto Rate Update Job Generate Loan Products Loan Prequalification Reporting
Spring Framework Non-AOP representation Cross Cutting Concerns Auto Rate Update Job Transaction Management Generate Loan Products Security Loan Prequalification Logging Reporting Performance Metrics
Spring Framework AOP representation Cross Cutting Concerns Logging Security Transaction Management AutoRate Update Job Generate Loan Products Loan Prequalification Reporting
Spring Framework Spring @ Work Business Objects / POJOs Spring Container Configuration Metadata produces Configured Ready-to-use System
Spring Framework Download the JAR files from, • http://www.springframework.org/download Copy them to the dependency folder. If you start afresh, you might need logging • Add a log4j.properties to the ROOT of class folder • Add the following to the file to direct all logging to console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p %c - %m%n log4j.rootLogger=INFO, stdout log4j.logger.org.springframework=DEBUG (or ERROR) Start coding Build your own preferred way using Ant, Maven, … Spring Installation
Spring Framework HelloWorldService.java HelloWorldServiceImpl.java package spring; public class HelloWorldImpl implements HelloWorldService { private String message; private HelloWorldImpl() { } public HelloWorldImpl(String message) { this.message = message; } public void sayHello() { System.out.println(“Hello “ + message); } public void setMessage(String message) { this.message = message; } } Traditional Hello World! package spring; public interface HelloWorldService { public void sayHello(); }
Spring Framework <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id=“helloWorldService“ class="spring.HelloWorldImpl"> <property name=“message"> <value>Welcome to Spring!</value> </property> </bean> </beans> * DTD version for the schema is also available and can be declared as under, <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN“ "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> Configuring (hello.xml)
Spring Framework package spring; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class HelloWorld { public static void main(String[] args) throws Exception { ClassPathResource resource = new ClassPathResource(“hello.xml”); BeanFactory factory = new XmlBeanFactory(resource); HelloWorldService helloWorldService = (HelloWorldService) factory.getBean("helloWorldService"); helloWorldService.sayHello(); } } The Actual Implementation – HelloWorld.java
Spring Framework A service bean using the EJB way, private OrderService orderService; public void doRequest(HttpServletRequest request) { Order order = createOrder(request); OrderService service = getOrderService(); service.createOrder(order); } private OrderService getOrderService() throws CreateException { if (orderService == null) { Context initial = new InitialContext(); Context ctx = (Context) initial.lookup(“java:comp/env”); Object ref = ctx.lookup(“ejb/OrderServiceHome”); OrderServiceHome home = (OrderServiceHome) PortableRemoteObject.narrow(ref, OrderService.class); orderService = home.create(); } return orderService; } IoC in an Enterprise Application
Spring Framework Magic the dependency injection way, private OrderService orderService; public void doRequest(HttpServletRequest request) { Order order = createOrder(request); orderService.createOrder(order); } public void setOrderService(OrderService service) { orderService = service; } IoC in an Enterprise Application
Spring Framework 03 The Core
Spring Framework may be POJO/EJB/WebService Spring’s world revolves all around Beans Generated using two different containers, • Bean Factory Provides basic support for dependency injection • Application Context Built over BeanFactory to provide support for i18N, events, and file resources. Wiring done using bean definitions • Specified as Configuration Metadata Spring Beans
Spring Framework Bean Factory Implementation of Factory design pattern. Creates associations between objects, doles out fully configured, ready to use objects. Manages all the beans in the container. 28
Spring Framework Instantiating Container • Using Bean Factories • In version 2.0 Resource resource = new FileSystemResource(“beans.xml”); BeanFactory factory = new XmlBeanFactory(resource); • In version 1.0 FileInputStream stream = new FileInputStream(“beans.xml”); BeanFactory factory = new XmlBeanFactory(stream); 29
Spring Framework Resource Interface • In-box wrappers available for, • UrlResource • ClassPathResource • FileSystemResource • ServletContextResource • InputStreamResource • ByteArrayResource • Also, provides for loading of resources such as images, css, js etc. in a web application. 30
Spring Framework Resource Interface • Resource Interface, • public interface Resource extends InputStreamSource • Methods, • boolean exists() • boolean isOpen() • InputStream getInputStream() • String getDescription() • often returns fully qualified file name or the actual URL • URL getURL() • File getFile() • String getFilename() • Resource createRelative(String relativePath) 31
Spring Framework Application Context • Aggregates information about the application that can be used by all components. • Various implementations are, • ClassPathXmlApplicationContext • FileSystemXmlApplicationContext • XmlWebApplicationContext • Instantiating, ApplicationContext context = new FileSystemXmlApplicationContext(“c:\spring\beans.xml”); 32
Spring Framework Application Context – Multiple Context’s • Loading multiple contexts String[] ctxs = new String[] { “ctx1.xml”, “ctx2.xml” }; • Loading hiererichal contexts ApplicationContext parent = new ClassPathXmlApplicationContext (“ctx1.xml”); ApplicationContext child = new FileSystemXmlApplicationContext(“ctx2.xml”, parent); 33
Spring Framework Configuration Metadata • Configuration can be done using, • XML configuration files • Java property files • Programmatically using API • Annotations • Spring JavaConfig* 34
Spring Framework Bean definition contains the following attributes, • id/name • class • scope: singleton/prototype/custom • constructor arguments • properties • auto wiring mode • dependency checking mode • lazy-initialization mode • initialization method • destruction method • and much more… Defining Bean
Spring Framework Sample Bean Definition • A basic bean definition, <beans> <bean id=“sampleBean" class=“spring.SampleSpringBeanClass“ scope=“singleton” auto-wire=“byName” dependency-check=“simple” lazy-init=“true” init-method=“myInitMethod” destroy-method=“myDestroyMethod” > <constructor-arg value=“Hello World” /> <property name=“prop1” value=“value1” /> <property name=“prop2” ref=“anotherBean” /> </bean> </beans> 36
Spring Framework Defining Bean – short-circuit • The arcane way of XML, <beans> <bean id=“sampleBean" class=“spring.SampleSpringBeanClass“> <property> <name>prop1</name> <value>value1</value> </property> </bean> </beans> • Short-hand notation • <property name=“…” value=“…” /> • <constructor-arg value=“…” /> • <property name=“…” ref=“…” /> • <entry key=“…” value=“…” /> • <entry key-ref=“key reference” value=“…” /> 37
Spring Framework Importing other resources inside another resource <beans> <import resource="services.xml"/> <import resource="resources/messageSource.xml"/> <import resource="/resources/themeSource.xml"/> <bean id="bean1" class="..."/> <bean id="bean2" class="..."/> </beans> Separating Concerns
Spring Framework In bean definition itself • Using one name in the id attribute • All other names using the “name” attribute • separated by comma, semi-colon, white space Using the <alias> element <alias name="fromName" alias="toName"/> Bean Aliases
Spring Framework Bean Scopes • By default, all Spring beans are singletons • Prototyped beans are useful when properties need to be set using Spring wiring <bean id=“example” class=“spring.MyExample” scope=“singleton” /> <bean id=“example” class =“spring.MyExample” scope=“prototype” /> <bean id=“example” class =“spring.MyExample” scope=“myScope” /> In Spring 1.0, <bean id=“example” class=“spring.MyExample” singleton=“false” /> 40
Spring Framework Bean Scopes • Scopes available, • singleton • prototype • request • session • global session • custom scope (since Spring 2.0+) 41
Spring Framework Constructor Injection Setter Injection <bean id=“helloWorldService“ class=“spring.HelloWorldImpl"> <property name=“message"> <value>Hello World!</value> </property> </bean> Prevents lengthy constructors Several ways to construct an object Multiple dependencies of same type Constructors pose a problem in case of inheritance Constructor v/s Setter Injection <bean id=“helloWorldService“ class=“spring.HelloWorldImpl"> <constructor-arg> <value>Hello World!</value> </constructor-arg> </bean> • Strong dependency contract • No superfluous setter’s • Dependent properties immutable
Spring Framework Example public class Foo(Bar bar, Car car) { //… } <bean name=“Foo” class=“Foo”> <constructor-arg><bean class=“Bar” /></constructor-arg> <constructor-arg><bean class=“Car” /></constructor-arg> </bean> Example public class Example(int years, String name) { //… } <bean name=“example” class=“Example”> <constructor-arg type=“int” value=“75000” /> <constructor-arg type=“java.lang.String” value=“Spring Enabled Message” /> </bean> <bean name=“example” class=“Example”> <constructor-arg index=“0” value=“75000” /> <constructor-arg index=“1” value=“Spring Enabled Message” /> </bean> Constructor Argument Resolution
Spring Framework Example <bean id=“EmailService” class=“spring.EmailServiceImpl”> <property name=“loginService”> <bean class=“spring.LDAPLoginService” /> </property> </bean> Remember • Can not reuse the inner-bean instance • Useful when we want to escape AOP proxying. Inner Beans
Spring Framework Auto Wiring • Four types of auto-wiring • byName Find a bean whose name is same as the name of the property being wired. • byType Find a single bean whose type matches the type of the property being wired. If more than one bean is found, UnsatisfiedDependencyExceptionwill be thrown. • constructor Match one or more beans in the container with the parameters of one of the constructors of the bean being wired. • autodetect Autowire by constructor first, then byType. 45
Spring Framework Auto Wiring - Examples <bean id=“pricingService” class=“….”> <property name=“pricingDao”> <ref bean=“pricingDao” /> </property> <property name=“ssnService”> <ref bean=“ssnService> </property> </bean> • By Name <bean id=“pricingService” class=“…” auto-wire=“byName” /> • By Type <bean id=“pricingService” class=“…” auto-wire=“byType” /> 46
Spring Framework Auto Wiring - Advanced • Mixing auto and explicit wiring <bean id=“pricingService” class=“…” autowire=“byName” > <property name=“ssnService”> <ref bean=“newSSNService” /> </property> </bean> • By-default wiring <beans default-autowire=“byName” > • Can pose problems while refactoring if, • Bean cannot be found • Bean is not the one, the service actually wants 47
Spring Framework Dependency Check • Four types of dependency checks, • none Properties that have no value are not set. • simple Performed for primitive types and collections, except collaborators. • object Performed only for collaborators. • all Performed for primitives, collections and colloborators. 48
Spring Framework Lazy Initialization • Specifying <bean id=“myBean” class=“…” lazy-init=“true” /> • By default lazy initialization <beans default-lazy-init=“true”> …. // various bean definitions </beans> 49
Spring Framework Example public class Example { public void setup() { //init method } public void tearDown() { //destruction } //… } <bean id=“example” class=“Example” init-method=“setup” destroy-method=“tearDown” /> Custom init & destroy