Spring
This presentation is the property of its rightful owner.
Sponsored Links
1 / 75

Spring PowerPoint PPT Presentation


  • 172 Views
  • Uploaded on
  • Presentation posted in: General

Spring. Bipin Jethwani. http://www.springsource.org /. What is Spring?. Spring simplifies Java development. Spring is an open source application framework and inversion of control container for the Java platform. Background. Originally created by Rod Johnson.

Download Presentation

Spring

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Spring

Spring

Bipin Jethwani


Spring

http://www.springsource.org/


Spring

What is Spring?


Spring

Spring simplifies Java development

Spring is an open source application framework

and inversion of control container for the

Java platform


Spring

Background

Originally created by Rod Johnson.

Described in his book Expert One-on-One: J2EE Design and Development.

The framework was first released under the Apache 2.0 license in June 2003.

Spring was created to address the complexity of enterprise application development, and makes it possible to use plain-vanilla JavaBeans to achieve things that were previously only possible with EJBs.

Spring’s usefulness isn’t limited to server-side development.

Any Java application can benefit from Spring in terms of simplicity,

testability, and loose coupling.


Spring

Spring’s primary features

  • Dependency Injection (DI)

  • Aspect-oriented programming (AOP)


Spring

Lightweight and minimally invasive development with plain old Java objects (POJOs).

Loose coupling through dependency injection and interface orientation.

Declarative programming through aspects and common conventions.

Boilerplate reduction through aspects and templates


Spring

  • package com.bjethwan.ejbs.session;

  • import javax.ejb.SessionBean;

  • import javax.ejb.SessionContext;

  • public class HelloWorldBean implements SessionBean{

  • public void ejbCreate(){ … }

  • public void ejbActivate(){ … }

  • public void ejbPassivate(){ … }

  • public void ejbRemove(){ … }

  • public void setSessionContext(SessionContextctx){ … }

  • public StringsayHello(){ return"HelloWorld";

  • }

  • }


Spring

The SessionBean interface would let you hook into the EJB’s lifecycle by implement- ing several lifecycle callback methods (those methods that start with ejb). Or I should rephrase that to say that the SessionBean interface would force you to hook into the EJB’s lifecycle, even if you didn’t need to. The bulk of the code in HelloWorldBean is there solely for the sake of the framework. This raises the question: who’s working for whom?


Spring

EJB 2 wasn’t alone when it came to being invasive. Other popular frameworks such as the earlier versions of Struts, WebWork, and Tapestry imposed themselves upon otherwise simple Java classes. These heavyweight frameworks forced developers to write classes that were littered with unnecessary code, locked into their framework, and were often difficult to write tests against.


Spring

The core features of the Spring Framework can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Although the Spring Framework does not impose any specific programming model, it has become popular in the Java community as an alternative to, replacement for, or even addition to the Enterprise JavaBean (EJB) model.


Spring

Spring avoids (as much as possible) littering your application code with its API. Spring almost never forces you to implement a Spring-specific interface or extend a Spring-specific class. Instead, the classes in a Spring-based application often have no indication that they’re being used by Spring. At worst, a class may be annotated with one of Spring’s annotations, but is otherwise a POJO.


Spring

  • package com.bjethwan.spring;

  • public class HelloWorldBean {

    • public String sayHello() {

    • return "Hello World";

    • }

  • }


Spring

Injecting Dependencies

The phrase dependency injection may sound intimidating, conjuring up notions of a complex programming technique or design pattern. But as it turns out, DI isn’t nearly as complex as it sounds.

Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). This can lead to highly coupled and hard-to-test code.


Spring

Tightly coupled to RescueDamselQuest

package com.springinaction.knights;

public class DamselRescuingKnight implements Knight {

private RescueDamselQuest quest;

public DamselRescuingKnight() {

quest = new RescueDamselQuest();

}

public void embarkOnQuest() throws QuestException { quest.embark();

}

}


Spring

With DI, on the other hand, objects are given their dependencies at creation time by some third party that coordinates each object in the system. Objects aren’t expected to create or obtain their dependencies—dependencies are injected into the objects that need them.


Spring

constructor injection

Quest is injected

package com.springinaction.knights;

public class BraveKnight implements Knight {

private Quest quest;

public BraveKnight(Quest quest) {

this.quest= quest;

}

public void embarkOnQuest() throws QuestException { quest.embark();

}

}

What’s more, the quest he’s given is typed as Quest, an interface that all quests implement. So BraveKnight could embark on a RescueDamselQuest, a SlayDragon- Quest, a MakeRoundTableRounderQuest, or any other Quest implementation he’s given.


Spring

The point here is that BraveKnight isn’t coupled to any specific implementation of Quest. It doesn’t matter to him what kind of quest he’s asked to embark upon, so long as it implements the Quest interface. That’s the key benefit of DI—loose coupling. If an object only knows about its dependencies by their interface (not by their implementation or how they’re instantiated), then the dependency can be swapped out with a different implementation without the depending object knowing the difference.


Spring

package com.springinaction.knights;

import static org.mockito.Mockito.*;

import org.junit.Test;

public class BraveKnightTest {

@Test

public void knightShouldEmbarkOnQuest() throws QuestException { Quest mockQuest = mock(Quest.class);

BraveKnightknight = new BraveKnight(mockQuest); knight.embarkOnQuest();

verify(mockQuest, times(1)).embark();

}

}


Spring

wiring

INJECTING A QUEST INTO A KNIGHT Now that your BraveKnight class is written in such a way that you can give him any quest you want, how can you specify which Quest to give him? The act of creating associations between application components is commonly referred to as wiring.


Spring

In Spring, there are many ways to wire components together, but a common approach has always been via XML. The following listing shows a simple Spring configuration file, knights.xml, that gives a BraveKnight a SlayDragonQuest.


Spring

<?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-3.0.xsd">

<bean id="knight" class="com.springinaction.knights.BraveKnight">

<constructor-arg ref="quest" />

</bean>

<bean id="quest" class="com.springinaction.knights.SlayDragonQuest" />

</beans>


Spring

application context

SEEING IT WORK In a Spring application, an application context loads bean definitions and wires them together. The Spring application context is fully responsible for the creation of and wiring of the objects that make up the application. Spring comes with several imple- mentations of its application context, each primarily differing only in how they load their configuration.


Spring

Because the beans in knights.xml are declared in an XML file, an appropriate choice for application context might be ClassPathXmlApplicationContext. This Spring context implementation loads the Spring context from one or more XML files located in the application’s classpath. The main() method in the following listing uses ClassPathXmlApplicationContext to load knights.xml and to get a reference to the Knight object.


Spring

Injecting through constructors

INJECTING OBJECT REFERENCES WITH CONSTRUCTORS


Spring

CREATING BEANS THROUGH FACTORY METHODS


Spring

consider the case of configuring a singleton3 class as a bean in Spring.

Singleton classes generally ensure that only one instance is created by only allowing creation through a static factory method. The Stage class in the following listing is a basic example of a singleton class.


Spring

package com.springinaction.knights; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class KnightMain { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("knights.xml"); Knight knight = (Knight) context.getBean("knight"); knight.embarkOnQuest(); } }


Spring

Bean scoping


Spring

By default, all Spring beans are singletons. When the container dispenses a bean (either through wiring or as the result of a call to the container’s getBean() method) it’ll always hand out the exact same instance of the bean. But there may be times when you need a unique instance of a bean each time it’s asked for. How can you override Spring’s default singleton nature?


Spring

When declaring a <bean> in Spring, you have the option of declaring a scope for that bean.

To force Spring to produce a new bean instance each time one is needed,

you should declare the bean’s scope attribute to be prototype.

For example, suppose that tickets for a performance are declared as a bean in Spring:

<bean id="ticket" class="com.bjethwan.Ticket“ scope="prototype“ />


Spring

Spring’s singleton beans only guarantee a single instance of the bean definition per the application context—nothing is stopping you from instantiating that same class in a more conventional way or even defining several <bean> declarations that instantiate the same class.


Spring

Initializing and destroying beans


Spring

When a bean is instantiated, it may be necessary to perform some initialization to get it into a usable state. Likewise, when the bean is no longer needed and is removed from the container, some cleanup may be in order. To accommodate setup and tear- down of beans, Spring provides hooks into the bean lifecycle.


Spring

To define setup and teardown for a bean, simply declare the <bean> with init- method and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly, destroy-method specifies a method that is called just before a bean is removed from the container.


Spring

DEFAULTING INIT-METHOD AND DESTROY-METHOD

If many of the beans in a context definition file will have initialization or destroy methods with the same name, you don’t have to declare init-method or destroy- method on each individual bean. Instead you can take advantage of the default- init-method and default-destroy-method attributes on the <beans> element:

<?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-3.0.xsd" default-init-method="turnOnLights" default-destroy-method="turnOffLights">... </beans>

(if those methods exist—otherwise nothing happens).


Spring

INJECTING INNER BEANS

We’ve seen that Kenny can play saxophone, piano, or any instrument that implements the Instrument interface. But it’s also true that the saxophone and piano beans could also be shared with any other bean by injecting them into an instrument property. So, not only can Kenny play any Instrument, any Instrumentalist can play the saxophone bean. In fact, it’s common for beans to be shared among other beans in an application. The problem is that Kenny’s concerned with the hygienic implications of sharing his saxophone with others.


Spring

Wiring properties with Spring’s p namespace


Spring

The p namespace has a schema URI of http://www.springframework.org/ schema/p. To use it, simply add a declaration for it in the Spring XML configuration: <?xml version="1.0"encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd">


Spring

With it declared, you can now use p:-prefixed attributes of the <bean> element to wire properties. An an example, look at the following declaration of the kenny bean:

<bean id="kenny" class="com.springinaction.springidol.Instrumentalist" p:song = "Jingle Bells" p:instrument-ref = "saxophone" />


Spring

Wiring collections


Spring

Up to now, you’ve seen how to use Spring to configure both simple property values (using the value attribute) and properties with references to other beans (using the ref attribute). But value and ref are only useful when your bean’s properties are sin- gular. How can Spring help you when your bean has properties that are plural—what if a property is a collection of values?


Spring

Spring offers four types of collection configuration elements that come in handy when configuring collections of values.


Spring

Applying aspects


Spring

Wiring with expressions


Spring

Spring 3

Spring Expression Language (SpEL)


Spring

<property name="count" value="#{5}"/>

The #{} markers are a clue to Spring that the content that they contain is a SpEL expression.

They could be mixed with non-SpEL values as well:

<property name="message" value="The value is #{5}"/>

Floating-point numbers can also be expressed in SpEL. For example:

<property name="frequency" value="#{89.7}"/>


Spring

<bean id="carl" class="com.springinaction.springidol.Instrumentalist"> <property name="song" value="#{kenny.song}" />

</bean>

Instrumentalist carl = new Instrumentalist(); carl.setSong(kenny.getSong());

Referring to another bean’s property using Spring Expression Language


Spring

What’s aspect-oriented programming?


Spring

System services such as logging, transaction management, and security often find their way into Listing 1.7 KnightMain.java loads the Spring context containing a knight. Load Spring context Get knight bean Use knight Licensed to Christian Cederquist <[email protected]> 11 Simplify ing Java development components whose core responsibility is something else. These system services are commonly referred to as cross-cutting concerns because they tend to cut across multiple components in a system.


Spring

In software development, functions that span multiple points of an application are called cross-cutting concerns. Typically, these cross-cutting concerns are conceptually separate from (but often embedded directly within) the application’s business logic. Separating these cross-cutting concerns from the business logic is where aspect- oriented programming (AOP) goes to work.


Spring

With AOP, you still define the common functionality in one place, but you can declaratively define how and where this functionality is applied without having to modify the class to which you’re applying the new feature.


Spring

Cross- cutting concerns can now be modularized into special classes called aspects.


Spring

This has two benefits. First, the logic for each concern is now in one place, as opposed to being scattered all over the code base. Second, our service modules are now cleaner since they only contain code for their primary concern (or core functionality) and second- ary concerns have been moved to aspects.


Spring

Defining AOP terminology


Spring

This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.

  • Aspects are often described in terms of

    • advice

    • pointcuts

    • join points.

The job of an aspect is called advice.

A join point is a point in the execution of the application where an aspect can be plugged in.

If advice defines the what and when of aspects, then pointcuts define the where. A pointcut definition matches one or more join points at which advice should be woven.


Spring

three dominant AOP frameworks:

 AspectJ (http://eclipse.org/aspectj)

 JBoss AOP (http://www.jboss.org/jbossaop)

 Spring AOP (http://www.springframework.org)


Spring

Spring aspects are implemented as proxies that wrap the target object. The proxy handles method calls, performs additional aspect logic, and then invokes the target method.

But method interception should suit most, if not all, of your needs. If you find yourself in need of more than method interception, you’ll want to complement Spring AOP with AspectJ.


Spring

In Spring AOP, pointcuts are defined using AspectJ’spointcut expression language.

The most important thing to know about AspectJpointcuts as they pertain to Spring AOP is that Spring only supports a subset of the pointcut designators available in AspectJ


Spring

Attempting to use any of AspectJ’s other designators will result in an IllegalArgument- Exception being thrown. As you browse through the supported designators, note that the execution desig- nator is the only one that actually performs matches. The other designators are used to limit those matches. This means that execution is the primary designator you’ll use in every pointcut definition you write. You’ll use the other designators to constrain the pointcut’s reach.


Spring

Using Spring’s bean() designator


Spring

Spring 2.5 introduced a new bean() designator that lets you identify beans by their ID within a pointcut expression. bean() takes a bean ID or name as an argument and limits the pointcut’s effect to that specific bean.

execution(* com.springinaction.springidol.Instrument.play()) and bean(eddie)

execution(* com.springinaction.springidol.Instrument.play()) and !bean(eddie)

In this case, the aspect’s advice will be woven into all beans whose ID isn’t eddie.


Spring

Declaring aspects in XML


Spring

Spring aspects can work with five kinds of advice:

 Before—The advice functionality takes place before the advised method is invoked.

 After—The advice functionality takes place after the advised method completes, regardless of the outcome.

 After-returning—The advice functionality takes place after the advised method successfully completes.

 After-throwing—The advice functionality takes place after the advised method throws an exception.

 Around—The advice wraps the advised method, providing some functionality before and after the advised method is invoked.


Spring

Using AOP, systemwide concerns blanket the components that they impact. This leaves the application components to focus on their specific business functionality.


  • Login