Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
-
Upload
arjun-thakur -
Category
Technology
-
view
533 -
download
3
description
Transcript of Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Spring Framework
1
Prepared & Presented byArjun
Know your trainer
2
Freelance corporate trainer. More than 2 years of strong hands-on experience in top MNCs in Java
and related technologies. More than 2 years of experience as a Java trainer.
Name: ArjunPhone : +91 9691053479Email: [email protected]
Clients / Previous Employers:
Agenda
3
Introduction to Spring framework Benefits of Spring framework Spring framework architecture Inversion of Control (IoC) Dependency Injection (DI)
Topics to be covered are:
Spring Framework
4
Light-weight comprehensive framework for building Java SE and Java EE applications
Created by Rod Johnson JavaBeans-based configuration management, applying Inversion-
of-Control principles, specifically using the Dependency Injection technique • Reduce dependencies of components on specific
implmentation of other components. • A core bean factory, which is usable globally
Generic abstraction layer for database transaction management
Key Features
5
Built-in generic strategies for JTA and a single JDBC DataSource This removes the dependency on a Java EE environment for
transaction support. Integration with persistence frameworks Hibernate, JDO and
iBATIS. MVC web application framework, built on core Spring functionality, supporting many technologies for generating views, including JSP. Extensive aspect-oriented programming (AOP) framework to
provide services such as transaction management. As with the Inversion-of-Control parts of the system, this aims to
improve the modularity of systems created using the framework.
Using Spring
6
Wiring of components through Dependency Injection Promotes de-coupling among the parts that make the
application Test-Driven Development (TDD)
POJO classes can be tested without being tied up with the framework
Declarative programming through AOP Easily configured aspects, esp. transaction support
Integration with other technologies EJB for J2EE Hibernate, iBatis, JDBC (for data access) Velocity (for presentation) Struts and WebWork (For web)
Spring Framework
7
Core Package
8
The fundamental part which provides the IoC and Dependency Injection features
BeanFactory, provides a sophisticated implementation of the factory pattern
Removes the need for programmatic singletons Decouple the configuration and specification of dependencies in
program logic.
Context Package
9
Provides a way to access objects in a framework-style Inherits its features from the beans package and adds support for
• internationalization (I18N) • event-propagation • resource-loading • transparent creation of contexts by
DAO Package
10
Provides a JDBC-abstraction layer that removes the need to do tedious
JDBC coding and parsing of database-vendor specific error codes Programmatic as well as declarative transaction management for
• classes implementing special interfaces • POJOs
ORM Package
11
The ORM package provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
Using the ORM package you can use all those O/R-mappers in combination with all the other features Spring offers, such as the simple declarative transaction management feature mentioned previously
AOP Package
12
Spring's AOP package provides an AOP Alliance-compliant aspect-oriented programming implementation • method-interceptors and pointcuts to cleanly decouple code
implementing functionality that should logically speaking be separated
Using source-level metadata functionality you can also incorporate all kinds of behavioral information into your code
MVC Package
13
Web package provides features, such as • multipart file-upload functionality, • the initialization of the IoC container using servlet listeners • A web-oriented application context. • Can be used together with WebWork or Struts,
Spring's MVC package provides a Model-View-Controller (MVC) implementation for web applications Provides a clean separation between domain model code and web
forms, and allows all the other features of the Spring Framework.
IoC Container
14
Introduction Basic Containers and Beans Dependencies The Application Context Developing a Spring Application
Inversion of Control
15
The Spring IoC container makes use of Java POJO classes and configuration metadata.
It produces a fully configured and executable system or application.
Introduction to IoC
16
Traditional software is developed with the application code “in control”• The application defines the “main”function/method/entry point• Calls the application’s components to perform processing
Frameworks invert this relationship and call the application code• “Don’t call us we’ll call you”• Framework provides the “main”function/method/entry point• Application code fits into the framework and is called when the
framework decides. A particular variant of IoC is “dependency injection”
Dependency Injection
17
Most frameworks use the “Service Lookup” approach to allow application code to find its dependencies.• e.g. J2EE code looks up resources via JNDI• CORBA applications find services via a Naming Service• The lookup mechanism is hard coded into the application code
Dependency Injection frameworks supply the resources that acomponent needs when initialising it• Component declares resources required (usually as interface
types)• Framework configuration defines concrete instances to use• Framework passes component the concrete resources at load
time “IoC containers” are “Dependency Injection” containers
Service Lookup vs. Dependency Injection
18
IoC Container
19
The org.springframework.beans and org.springframework.contextpackages provide the basis for the Spring Framework's IoC container.
BeanFactory interfaceprovides an advanced configuration mechanism capable of managing
objects of any nature. ApplicationContext interface , a sub interface of BeanFactory is used
for• Easier integration with Spring's AOP features,• Message resource handling (in internationalization),• Event propagation• Specific contexts such as the WebApplicationContext
Container and Beans
20
A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container
The beans, and the dependencies between them, are reflected in the configuration metadata used by a container.
org.springframework.beans.factory.BeanFactory is the representation of the Spring IoC container, it’s responsible for:• containing and managing beans,• instantiating or sourcing application objects• configuring such objects• assembling the dependencies between objects.
The Container
21
There are a number of implementations of the BeanFactory interface The most commonly used BeanFactory implementation is the
XmlBeanFactory class. The XmlBeanFactory takes the XML configuration metadata and uses
it to create a fully configured system or application.
Configuration Meta Data
22
The meta-data informs the Spring container as to how to “instantiate, configure, and assemble [the objects in your application]”.
XML-based metadata is the most commonly used form of configuration metadata.
Configuration consists of at least one bean definition that the container must manage, but could be more than one bean definition.
When using XML-based configuration metadata, these beans are configured as <bean/> elements inside a top-level <beans/> element.
Simple XML Configuration
23
<?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.5.xsd"> <bean id="..." class="..."> <!--collaborators and configuration for this bean go here --> </bean> <bean id="..." class="..."> <!--collaborators and configuration for this bean go here --> </bean> <!--more bean definitions go here --> </beans>
Instantiating a Container
24
ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"services.xml", "daos.xml"});
// an ApplicationContext is also a BeanFactory (via inheritance)
BeanFactory factory = context;
The Bean
25
The container manages the beans , and they are are created using the configuration metadata.
Bean definitions are represented as BeanDefinition objects, which contain the following metadata:
package-qualified class name: typically this is the actual implementation class of the bean being defined.
bean behavioral configuration elements, • which state how the bean should behave in the container
(scope, lifecycle callbacks etc.,). references to other beans
• which are needed for the bean to do its work; these references are also called collaborators or dependencies.
other configuration settings • An example would be the number of connections to use in a
bean that manages a connection pool, or the size limit of the pool.
Benefits of Dependency Injection
26
Flexible • Avoid adding lookup code in business logic
Testable • No need to depend on external resources or containers for
testing
Maintainable • Promotes a consistent approach across all applications and
teams• Allows reuse in different application environments by changing
configuration files instead of code
Dependency Injection
27
BeanFactory interface XmlBeanFactory implementation Bean configuration file Constructor dependency Injection
• Dependencies are provided through the constructors of the component
Setter dependency injection • Dependencies are provided through the JavaBeanstyle setter
methods of the component • More popular than Constructor dependency injection
Beans Injection Parameters
BeanFactory Class
28
BeanFactory object is responsible for managing beans and their dependencies
Your application interacts with Spring's DI container through BeanFactory interface• BeanFactory object has to be created by the application typically
XmlBeanFactory• BeanFactory object, when it gets created, read bean
configuration file and performs the wiring• Once created, the application can access the beans via
BeanFactory interface XmlBeanFactory
• Convenience extension of DefaultListableBeanFactory that reads bean definitions from an XML document
Beans
29
The term “bean” is used to refer any component managed by the BeanFactory
The “beans” are in the form of JavaBeans (in most cases) • no arg constructor • getter and setter methods for the properties
Beans are singletons by default Properties
• the beans may be simple values or references to other beans
The Bean – A Java Class
30
public class Example {private int empid;private String empname;public int getEmpid() {return empid;}public void setEmpid(int empid) {this.empid = empid;}public String getEmpname() {return empname;}public void setEmpname(String empname) {this.empname = empname;}public Example() {super();}} // no arg constructor
Injecting Simple Values–XML File
31
Each bean is defined using <bean> tag under the root of the <beans> tag
The id attribute is used to give the bean its default name The class attribute specifies the type of the bean
<bean id="firstBean" class="com.training.Example"> <property name="empname"> <value>ramesh</value> </property> <property name="empid"><value>100</value></property> </bean> </beans>
Injecting Simple Values–XML File
32
Each bean is defined using <bean> tag under the root of the <beans> tag
The id attribute is used to give the bean its default name The class attribute specifies the type of the bean
<bean id="firstBean" class="com.training.Example"> <property name="empname"> <value>ramesh</value> </property> <property name="empid"><value>100</value></property> </bean> </beans>
Spring Application
33
import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.FileSystemResource;
public class TestExample { public static void main(String[] args) { BeanFactory bfact = new XmlBeanFactory(new FileSystemResource("mybean.xml")); Example exObj = (Example)bfact.getBean("firstBean"); System.out.println(exObj.getEmpid()); System.out.println(exObj.getEmpname()); } }
Injection Parameter Types
34
Spring supports various kinds of injection parameters• Simple values• Beans in the same factory• Beans in another factory• Collections• Externally defined properties
You can use these types for both setter or constructor injections
Injecting Bean into the same Factory
35
Used when you need to inject one bean into another (target bean) Configure both beans first Configure an injection using <ref> tag in the target bean's <property>
or <constructor-arg> The type being injected does not have to be the exact type defined
on the target if the type defined on the target is an interface, the type being
injected must be an implementation of it if the type defined on the target is a class, the type being injected
can be the same type or sub-type
Constructor Injection
36
All dependencies injected via constructor arguments – Requires potentially complex constructor argument lists
Avoids reliance on get/set naming conventions – e.g. addStateObserver()
Less flexible initialisation – Need a constructor per configuration option
Can be difficult to understand – Rely on ordering of parameters
Constructor Dependency Injection (code snippet)
37
public class Invoice { private Items item; private String customer; private double amount; public Invoice(Items item) { this.item = item; } public Invoice() { super(); } // Set/Get Methods }
public class Items { private int itemno; private String itemname;
public Items() { super(); } // Set/Get Methods }
Constructor Dependency Injection (code snippet)
38
public class TestConstDepend { public static void main(String[] args) { BeanFactory bf = new XmlBeanFactory(new FileSystemResource("mybeandef.xml")); Invoice inv = (Invoice)bf.getBean("Invoice"); System.out.println(inv.getItem()); System.out.println(inv.getCustomer()); System.out.println(inv.getAmount()); } }
Setter Injection
39
All dependencies injected via setter methods – No need for constructors
Allows flexible initialisation – Any set of properties can be initialised
Named properties allow for readable configuration data – Clear what is being injected
Requires JavaBean conventions to be followed – Non standard method names are problematic
Can result in invalid object configurations – Need post initialisation checking methods
Setter Injection (code snippet)
40
public class Policy { private int policyCode; private String policyName; public Policy(int policyCode, String policyName) { this.policyCode = policyCode; this.policyName = policyName; } public Policy() { super(); } //SET-GET Methods }
public class Insurance { private int policynumber; private Policy policyData; public Policy getPolicyData() { return policyData; } public void setPolicyData(Policy policyData) { this.policyData = policyData; } //SET-GET Methods }
Setter Injection (code snippet)
41
public class TestSetterDependcy { public static void main(String[] args) { BeanFactory beanFact = new XmlBeanFactory (new FileSystemResource("myBean.xml"));
Insurance ins =(Insurance)beanFact.getBean("Insurance"); System.out.println("Policy Number"+ins.getPolicynumber());
System.out.println("Policy Code“ + ins.getPolicyData().getPolicyCode());
System.out.println("Policy Holder Name"+ ins.getPolicyData().getPolicyName());
} }
Setter Injection (code snippet)
42
<beans><bean id="Insurance" class="com.training.Insurance"><property name="policynumber“ <value>2345</value></property><property name="policyData"><ref local="Policy"/></property></bean>
<bean id="Policy" class="com.training.Policy"><property name="policyCode"><value>100</value></property><property name="policyName"><value>LifeInsurance</value></property></bean>
</beans>
Thank You
43