the power of enterprise java frameworks
DESCRIPTION
Topics: - What is an Enterprise Java Framework - Overview of popular Enterprise Java Frameworks - The most popular Enterprise Java framework - Spring Framework - ConclusionTRANSCRIPT
© SkywideSoft Technology Limited 1
The Power of Enterprise Java Frameworks
• Clarence Ho • Independent Consultant, Author, Java EE Architect • http://www.skywidesoft.com • [email protected]
• Presentation can be downloaded from: • http://www.skywidesoft.com/index.php/seminar
© SkywideSoft Technology Limited 2
• What is an Enterprise Java Framework?
• Overview of popular Enterprise Java Frameworks
• The most popular Enterprise Java framework - Spring Framework
• Resources
• Conclusion
• Q&A
Outline
© SkywideSoft Technology Limited 3
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 4
What is a software framework?
Source: Wikipedia
• A software framework is an abstraction in which software providing generic functionality can be selectively changed by user code, thus providing application specific software.
• A software framework is a universal, reusable software platform used to develop applications, products and solutions.
• Software Frameworks include support programs, compilers, code libraries, an application programming interface (API) and tool sets that bring together all the different components to enable development of a project or solution.
© SkywideSoft Technology Limited 5
What is a software framework? (cont.)
Source: Wikipedia
1. Inversion of control - In a framework, unlike in libraries or normal user applications, the overall program's flow of control is not dictated by the caller, but by the framework
2. Default behavior - A framework has a default behavior. This default behavior must actually be some useful behavior and not a series of no-ops.
3. Extensibility - A framework can be extended by the user usually by selective overriding or specialized by user code providing specific functionality.
4. Non-modifiable framework code - The framework code, in general, is not allowed to be modified. Users can extend the framework, but not modify its code.
Frameworks contain key distinguishing features that separate them from normal libraries:
© SkywideSoft Technology Limited 6
What is an application framework?
Source: Wikipedia
An application framework consists of a software framework used by software developers to implement the standard structure of an application for a specific development environment (such as a standalone program or a web application).
Application frameworks became popular with the rise of multi-tiers enterprise applications since these tended to promote a standard structure for applications. Programmers find it much simpler to program when using a standard framework, since this defines the underlying code structure of the application in advance. Developers usually use object-oriented programming techniques to implement frameworks such that the unique parts of an application can simply inherit from pre-existing classes in the framework.
© SkywideSoft Technology Limited 7
What is an enterprise application framework?
An application framework designed for the implementation of enterprise class applications.
In addition to an application framework, an enterprise application framework should supports the development of a layered architecture, and provide services that can address the requirements on performance, scalability, and availability.
Layers within an enterprise application: - Persistence Layer - Services (Business Logic) Layer - Presentation Layer - Integration Layer (Web Services, Message-based)
Services: - Security - Transaction (local and global transactions) - Caching - Task scheduling and asynchronous task execution - Management and monitoring - Testing - and many more …
© SkywideSoft Technology Limited 8
What is an enterprise Java framework?
An enterprise application framework designed for the Java language.
Components: - Dependency Injection - AOP (Aspect Oriented Programming) - Persistence - Transactions - Presentation Framework - Web Services - Messaging - Testing
© SkywideSoft Technology Limited 9
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 10
IOC and DI – Main Purpose
Source: Pro Spring 3
At its core, IOC, and therefore DI, aims to offer a simpler mechanism for provisioning component dependencies (often referred to as an object’s collaborators) and managing these dependencies throughout their life cycles. A component that requires certain dependencies is often referred to as the dependent object or, in the case of IOC, the target.
Types of IOC:
Dependency Pull
Contextualized Dependency Lookup (CDL)
Dependency Injection
• Constructor Injection
• Setter Injection
© SkywideSoft Technology Limited 11
Type of IOC – Dependency Pull
Examples:
- EJB (prior to version 2.1)
- Spring (BeanFactory or ApplicationContext)
Source: Pro Spring 3
© SkywideSoft Technology Limited 12
Type of IOC – Dependency Pull (cont.)
Source: Pro Spring 3
public static void main(String[] args) throws Exception { // get the bean factory BeanFactory factory = getBeanFactory(); // get the target via dependency pull MessageRenderer mr = (MessageRenderer) factory.getBean("renderer"); // invoke target’s operation mr.render(); }
Dependency Pull in Spring:
© SkywideSoft Technology Limited 13
Type of IOC – Contextual Dependency Lookup
Source: Pro Spring 3
Contextualized Dependency Lookup (CDL) is similar, in some respects, to Dependency Pull, but in CDL, lookup is performed against the container that is managing the resource, not from some central registry, and it is usually performed at some set point.
© SkywideSoft Technology Limited 14
Type of IOC – CDL (cont.)
Source: Pro Spring 3
public interface ManagedComponent { public void performLookup(Container container); }
An interface for dependent object:
public interface Container { public Object getDependency(String key); }
package com.apress.prospring3.ch4; public class ContextualizedDependencyLookup implements ManagedComponent { private Dependency dependency; public void performLookup(Container container) { this.dependency = (Dependency) container.getDependency("myDependency"); } }
A container interface:
Obtaining dependency when container is ready:
© SkywideSoft Technology Limited 15
Type of IOC – Dependency Injection
Source: Pro Spring 3
Spring’s Dependency Injection Mechanism:
public class ConstructorInjection { private Dependency dependency; public ConstructorInjection(Dependency dependency) { this.dependency = dependency; } }
Constructor Injection:
public class SetterInjection { private Dependency dependency; public void setDependency(Dependency dependency) { this.dependency = dependency; } }
Setter Injection:
© SkywideSoft Technology Limited 16
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 17
JEE 6
Source: Pro Spring 3
• A collection of JCP (Java Community Process) standards
• Implemented by all JEE compliant application servers
Oracle Glassfish 3.1 Oracle WebLogic 12c
IBM WebSphere 8.5
JBoss Application Server 7.1
Apache TomEE 1.0.0
© SkywideSoft Technology Limited 18
JEE 6 – Features/API Overview
Source: JavaOne Presentation by IBM
© SkywideSoft Technology Limited 19
JBoss Seam Framework
• Designed around JEE standards
• Mainly supported by JBoss Application Server
• Provide a micro-container for use with other AS or Tomcat
• Tightly integrates with other JBoss frameworks and libraries
© SkywideSoft Technology Limited 20
Jboss Seam Framework – Features/API Overview
Source: JavaOne Presentation by IBM
Hibernate
RichFaces
© SkywideSoft Technology Limited 21
Google Guice
• Reference implementation of JSR330 (Dependency Injection for Java)
• Focus on DI only
• Not a full blown enterprise Java framework
© SkywideSoft Technology Limited 22
Spring Framework
• The most popular enterprise Java framework
• Support all major application servers and web containers
• Support major JEE standards
• Integrates with other popular opensource frameworks and libraries
© SkywideSoft Technology Limited 23
Spring Framework – Features/API Overview
Source: JavaOne Presentation by IBM
© SkywideSoft Technology Limited 24
JEE vs Spring – Features/API Overview
Source: JavaOne Presentation by IBM
* Similar patterns for validation, remoting, security, scheduling, XML binding, JMX, JCA, JavaMail, caching * Spring also support EJB 3.1, but not CDI
© SkywideSoft Technology Limited 25
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 26
Spring Framework – Main Features
Feature Description Sub-proj.
IOC Container Configuration of application components and lifecycle management of Java objects, done mainly via Dependency Injection
AOP Enables implementation of cross-cutting routines
Data Access Working with relational database management systems on the Java platform using JDBC and object-relational mapping tools and with NoSQL databases
Spring Data projects
Transaction Management
Unifies several transaction management APIs (JDBC, JPA, JTA, etc.) and coordinates transactions for Java objects.
Model-view-controller
An HTTP- and servlet-based framework providing hooks for extension and customization for web applications and RESTful Web Services.
Authentication & Authorization
Configurable security processes that support a range of standards, protocols, tools and practices via the Spring Security sub-project
Spring Security
Remote Management
Configurative exposure and management of Java objects for local or remote configuration via JMX
Messaging Configurative registration of message listener objects for transparent message-consumption from message queues via JMS, improvement of message sending over standard JMS APIs
Testing support classes for writing unit tests and integration tests
Source: Wikipedia
© SkywideSoft Technology Limited 27
Spring Framework – Latest Features (3.X)
Feature Description Version
Java-based Configuration Use Java classes to configure Spring’s ApplicationContext (Spring JavaConfig was merged into the core Spring Framework since 3.0).
3.0
Embedded JDBC DataSource
Embedded database support (by using the <jdbc:embedded-database id="dataSource" type="H2"> tag)
3.1
Validation with Type Conversion and Formatting
Spring 3 introduce a new type conversion and formatting system, and support of JSR303 Bean Validation API.
3.0
Persistence with Spring Data JPA
Spring Data JPA’s Repository abstraction greatly simplifies the development of persistence layer with JPA.
3.0
Spring MVC Improved support of RESTful-WS. 3.1
Spring Expression Language A powerful expression language that supports querying and manipulating an object graph at run time.
3.0
Profiles A profile instructs Spring to configure only the ApplicationContext that was defined when the specified profile was active
3.1
Cache Abstraction A caching abstraction layer that allows consistent use of various caching solutions with minimal impact on the code.
3.1
TaskScheduler Abstraction Provides a simple way to schedule tasks and supports most typical requirements.
3.0
© SkywideSoft Technology Limited 28
Other Useful Spring Projects
Project Description Version
Spring Security Configurable security processes that support a range of standards, protocols, tools and practices
3.1.2
Spring Data An umbrella project includes many modules that simplifies the development of persistence layer with various data sources (e.g. JPA, NoSQL, JDBC, Hadoop, etc.)
1.X
Spring Batch Provides a standard template and framework for implementing and executing various kinds of batch jobs in an enterprise environment.
2.1.8
Spring Integration Provides an excellent integration environment for enterprise applications.
2.1.3
Spring WebFlow Building on top of Spring MVC’s foundation, Spring Web Flow was designed to provide advanced support for organizing the flows inside a web application.
2.3.1
Spring Mobile An extension to Spring MVC that aims to simplify the development of mobile web applications.
1.0.0
Spring Roo A rapid application development solution for Spring-based enterprise applications
1.2.2
SpringSource Tool Suite
An IDE tools with Eclipse and Spring IDE bundled, together witn numerous tools for developing Spring applications.
3.0.0
© SkywideSoft Technology Limited 29
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 30
Spring Framework – Highlights of Main Features
• Spring Beans Configuration
• Profiles
• Spring AOP
• Persistence with Hibernate and Spring Data JPA
• Spring Expression Language
• Spring MVC
© SkywideSoft Technology Limited 31
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 32
Spring Beans Configuration
• Basic Configuration (XML and Annotations)
• Beans Life-cycle
• Configuration Using Java Classes
© SkywideSoft Technology Limited 33
Basic Configuration (XML and Annotations)
public interface MessageProvider { public String getMessage(); }
public class HelloWorldMessageProvider implements MessageProvider { public String getMessage() { return "Hello World!"; } }
A simple interface and implementation.
© SkywideSoft Technology Limited 34
Basic Configuration (XML and Annotations)
public interface MessageRenderer { public void render(); public void setMessageProvider(MessageProvider provider); public MessageProvider getMessageProvider(); }
public class StandardOutMessageRenderer implements MessageRenderer { private MessageProvider messageProvider = null; public void render() { if (messageProvider == null) { throw new RuntimeException( "You must set the property messageProvider of class:"+ StandardOutMessageRenderer.class.getName()); } System.out.println(messageProvider.getMessage()); } public void setMessageProvider(MessageProvider provider) { this.messageProvider = provider; } public MessageProvider getMessageProvider() { return this.messageProvider; } }
Interface and implementation of a dependent object.
© SkywideSoft Technology Limited 35
Basic Configuration (XML and Annotations)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> <!-- XML configuration of Spring Beans --> <bean id="messageRenderer“ class="com.apress.prospring3.ch4.xml.StandardOutMessageRenderer“> <property name="messageProvider"> <ref bean="messageProvider"/> </property> </bean> <bean id="messageProvider" class="com.apress.prospring3.ch4.xml.HelloWorldMessageProvider"/> </beans>
XML Configuration of Spring ApplicationContext.
© SkywideSoft Technology Limited 36
Basic Configuration (XML and Annotations)
<!-- Setter injection --> <bean id="messageRenderer“ class="com.apress.prospring3.ch4.xml.StandardOutMessageRenderer“> <property name="messageProvider"> <ref bean="messageProvider"/> </property> </bean> <!-- Setter injection with p namespace --> <bean id="messageRenderer" class="com.apress.prospring3.ch4.xml.StandardOutMessageRenderer" p:messageProvider-ref="messageProvider"/> <!-- Constructor injection --> <bean id="messageProvider" class="com.apress.prospring3.ch4.xml.ConfigurableMessageProvider"> <constructor-arg> <value>This is a configurable message</value> </constructor-arg> </bean> <!-- Constructor injection with c namespace --> <bean id="messageProvide" class="com.apress.prospring3.ch4.xml.ConfigurableMessageProvider" c:message="This is a configurable message"/>
Setter and Constructor Injection.
© SkywideSoft Technology Limited 37
Basic Configuration (XML and Annotations)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> <!– Scan for Spring Beans Annotations --> <context:annotation-config/> <context:component-scan base-package="com.apress.prospring3.ch4.annotation"/> </beans>
Annotation Configuration of Spring ApplicationContext.
© SkywideSoft Technology Limited 38
Basic Configuration (XML and Annotations)
@Service("messageProvider") public class HelloWorldMessageProvider implements MessageProvider {
Setter Injection with Annotations.
@Service("messageRenderer") public class StandardOutMessageRenderer implements MessageRenderer { … @Autowired public void setMessageProvider(MessageProvider provider) { this.messageProvider = provider; } … }
© SkywideSoft Technology Limited 39
Basic Configuration (XML and Annotations)
@Service("messageProvider") public class HelloWorldMessageProvider implements MessageProvider {
Constructor Injection with Annotations.
@Service("messageRenderer") public class StandardOutMessageRenderer implements MessageRenderer { … @Autowired public StandardOutMessageRenderer(MessageProvider provider) { this.messageProvider = provider; } … }
© SkywideSoft Technology Limited 40
Beans Life-cycle
© SkywideSoft Technology Limited 41
Configuration Using Java Classes
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="messageRenderer" class="com.apress.prospring3.ch5.javaconfig.StandardOutMessageRenderer" p:messageProvider-ref="messageProvider"/> <bean id="messageProvider" class="com.apress.prospring3.ch5.javaconfig.ConfigurableMessageProvider" c:message="This is a configurable message"/> </beans>
A simple XML configuration.
© SkywideSoft Technology Limited 42
Configuration Using Java Classes
public class JavaConfigSimpleExample { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:app-context.xml"); MessageRenderer renderer = ctx.getBean("messageRenderer", MessageRenderer.class); renderer.render(); } }
Bootstrap Spring ApplicationContext using XML configuration.
© SkywideSoft Technology Limited 43
Configuration Using Java Classes
@Configuration public class AppConfig { // XML: // <bean id="messageProvider“ class="com.apress.prospring3.ch5.javaconfig.ConfigurableMessageProvider"/> @Bean public MessageProvider messageProvider() { return new ConfigurableMessageProvider(); } // XML: // <bean id="messageRenderer" class="com.apress.prospring3.ch5.javaconfig.StandardOutMessageRenderer" // p:messageProvider-ref="messageProvider"/> @Bean public MessageRenderer messageRenderer() { MessageRenderer renderer = new StandardOutMessageRenderer(); // Setter injection renderer.setMessageProvider(messageProvider()); return renderer; } }
A simple Java configuration class.
© SkywideSoft Technology Limited 44
Configuration Using Java Classes
public class JavaConfigSimpleExample { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); MessageRenderer renderer = ctx.getBean("messageRenderer", MessageRenderer.class); renderer.render(); } }
Bootstrap Spring ApplicationContext using Java classes.
© SkywideSoft Technology Limited 45
Configuration Using Java Classes
@Configuration @Import(OtherConfig.class) // XML: <import resource="classpath:events/events.xml") @ImportResource(value="classpath:events/events.xml") // XML: <context:property-placeholder location="classpath:message.properties"/> @PropertySource(value="classpath:message.properties") // XML: <context:component-scan base-package="com.apress.prospring3.ch5.context"/> @ComponentScan(basePackages={"com.apress.prospring3.ch5.context"}) @EnableTransactionManagement public class AppConfig { @Autowired Environment env; // XML: // <bean id="messageProvider" class="com.apress.prospring3.ch5.javaconfig.ConfigurableMessageProvider"/> @Bean @Lazy(value=true) //XML <bean .... lazy-init="true"/> public MessageProvider messageProvider() { // Constructor injection return new ConfigurableMessageProvider(env.getProperty("message")); }
More Java configurations.
© SkywideSoft Technology Limited 46
Configuration Using Java Classes
// XML: // <bean id="messageRenderer“ class="com.apress.prospring3.ch5.javaconfig.StandardOutMessageRenderer" // p:messageProvider-ref="messageProvider"/> @Bean(name="messageRenderer") @Scope(value="prototype") // XML: <bean ... scope="prototype"/> @DependsOn(value="messageProvider") // XML: <bean ... depends-on="messageProvider"/> public MessageRenderer messageRenderer() { MessageRenderer renderer = new StandardOutMessageRenderer(); // Setter injection renderer.setMessageProvider(messageProvider()); return renderer; } }
More Java configurations.
© SkywideSoft Technology Limited 47
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 48
Spring Beans Configuration
• Define beans for various application profiles
• Import configurations from all possible profiles
• Set the active profile in different ways
1. Programmatically
2. Web Deployment Descriptor (web.xml)
3. JVM properties during startup
© SkywideSoft Technology Limited 49
Define Beans for Various Profiles
public class Food { private String name; public Food() { } public Food(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Example: a food provider for kindergarten and high school.
The Food class:
© SkywideSoft Technology Limited 50
Define Beans for Various Profiles
public interface FoodProviderService { public List<Food> provideLunchSet(); }
Example: a food provider for kindergarten and high school.
The FoodProviderService interface:
© SkywideSoft Technology Limited 51
Define Beans for Various Profiles
package com.apress.prospring3.ch5.profile.kindergarten; import java.util.ArrayList; import java.util.List; import com.apress.prospring3.ch5.profile.Food; import com.apress.prospring3.ch5.profile.FoodProviderService; public class FoodProviderServiceImpl implements FoodProviderService { public List<Food> provideLunchSet() { List<Food> lunchSet = new ArrayList<Food>(); lunchSet.add(new Food("Milk")); lunchSet.add(new Food("Biscuits")); return lunchSet; } }
Example: a food provider for kindergarten and high school.
The FoodProviderServiceImpl class for kindergarten profile:
© SkywideSoft Technology Limited 52
Define Beans for Various Profiles
package com.apress.prospring3.ch5.profile.highschool; import java.util.ArrayList; import java.util.List; import com.apress.prospring3.ch5.profile.Food; import com.apress.prospring3.ch5.profile.FoodProviderService; public class FoodProviderServiceImpl implements FoodProviderService { public List<Food> provideLunchSet() { List<Food> lunchSet = new ArrayList<Food>(); lunchSet.add(new Food("Coke")); lunchSet.add(new Food("Hamburger")); lunchSet.add(new Food("French Fries")); return lunchSet; } }
Example: a food provider for kindergarten and high school.
The FoodProviderServiceImpl class for high school profile:
© SkywideSoft Technology Limited 53
Define Beans for Various Profiles
<?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.1.xsd" profile="kindergarten"> <bean id="foodProviderService" class="com.apress.prospring3.ch5.profile.kindergarten.FoodProviderServiceImpl"/> </beans>
Example: a food provider for kindergarten and high school.
The XML config file for kindergarten profile (kindergarten-config.xml):
© SkywideSoft Technology Limited 54
Define Beans for Various Profiles
<?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.1.xsd" profile="highschool"> <bean id="foodProviderService" class="com.apress.prospring3.ch5.profile.highschool.FoodProviderServiceImpl"/> </beans>
Example: a food provider for kindergarten and high school.
The XML config file for high school profile (highschool-config.xml):
© SkywideSoft Technology Limited 55
Define Beans for Various Profiles
public class ProfileXmlConfigExample { public static void main(String[] args) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.getEnvironment().setActiveProfiles("kindergarten"); ctx.load("classpath:profile/*-config.xml"); ctx.refresh(); FoodProviderService foodProviderService = ctx.getBean("foodProviderService", FoodProviderService.class); List<Food> lunchSet = foodProviderService.provideLunchSet(); for (Food food: lunchSet) { System.out.println("Food: " + food.getName()); } } }
Example: a food provider for kindergarten and high school.
Testing program with kindergarten profile activated:
Output: Food: Milk Food: Biscuits
© SkywideSoft Technology Limited 56
Define Beans for Various Profiles
public class ProfileXmlConfigExample { public static void main(String[] args) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.getEnvironment().setActiveProfiles(“highschool"); ctx.load("classpath:profile/*-config.xml"); ctx.refresh(); FoodProviderService foodProviderService = ctx.getBean("foodProviderService", FoodProviderService.class); List<Food> lunchSet = foodProviderService.provideLunchSet(); for (Food food: lunchSet) { System.out.println("Food: " + food.getName()); } } }
Example: a food provider for kindergarten and high school.
Testing program with highschool profile activated:
Output: Food: Coke Food: Hamburger Food: French Fries
© SkywideSoft Technology Limited 57
Configure Active Profiles
Configure active profile with JVM argument
© SkywideSoft Technology Limited 58
Configure Active Profiles
Configure active profile with JVM argument (in WebSphere)
© SkywideSoft Technology Limited 59
Configure Active Profiles
Configure active profile in Web Deployment Descriptor (web.xml)
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>spring.profiles.active</param-name> <param-value>kindergarten</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/*-config.xml </param-value> </context-param> …
© SkywideSoft Technology Limited 60
Profiles - Conclusion
• Configure Spring beans for different application environments
• Platform (dev, sit, uat, prd)
• Database (oracle, mysql)
• Application specific (kindergarten, highschool)
• When setting active profile with JVM argument, the same application file (e.g. jar, war, ear file, etc.) can be deployed to different environments, which simplifies the deployment process.
© SkywideSoft Technology Limited 61
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 62
Spring AOP
• Key Concepts
• Spring AOP Architecture
• Advice Types in Spring
• Configure AOP in Spring
• Configuring AOP Declaratively
• Using @AspectJ-Style Annotations
© SkywideSoft Technology Limited 63
Spring AOP – Key Concepts
Concept Description
Joinpoints A well-defined point during the execution of your application. Typical examples of joinpoints include a call to a method, the Method Invocation itself, class initialization, and object instantiation. Joinpoints are a core concept of AOP and define the points in your application at which you can insert additional logic using AOP.
Advice The code that is executed at a particular joinpoint is the advice. There are many different types of advice, such as before, which executes before the joinpoint, and after, which executes after it.
Pointcuts A pointcut is a collection of joinpoints that you use to define when advice should be executed. A typical joinpoint is a Method Invocation. A typical pointcut is the collection of all Method Invocations in a particular class.
Aspects An aspect is the combination of advice and pointcuts. This combination results in a definition of the logic that should be included in the application and where it should execute.
Weaving This is the process of actually inserting aspects into the application code at the appropriate point. Mechanisms include compile-time weaving and load-time weaving.
Target An object whose execution flow is modified by some AOP process is referred to as the target object. Often you see the target object referred to as the advised object.
© SkywideSoft Technology Limited 64
Spring AOP – Architecture
The core architecture of Spring AOP is based around proxies.
© SkywideSoft Technology Limited 65
Spring AOP – Advice Types
Advice Type Description
Before Using before advice, you can perform custom processing before a joinpoint executes. Because a joinpoint in Spring is always a Method Invocation, this essentially allows you to perform preprocessing before the method executes.
After returning After-returning advice is executed after the Method Invocation at the joinpoint has finished executing and has returned a value.
After (finally) After-returning advice is executed only when the advised method completes normally. However, the after (finally) advice will be executed no matter the result of the advised method. The advice is executed even when the advised method fails and an exception is thrown.
Around In Spring, around advice is modeled using the AOP Alliance standard of a method interceptor. Your advice is allowed to execute before and after the Method Invocation, and you can control the point at which the Method Invocation is allowed to proceed. You can choose to bypass the method altogether if you want, providing your own implementation of the logic.
Throws Throws advice is executed after a Method Invocation returns, but only if that invocation threw an exception. It is possible for a throws advice to catch only specific exceptions, and if you choose to do so, you can access the method that threw the exception, the arguments passed into the invocation, and the target of the invocation.
© SkywideSoft Technology Limited 66
Spring AOP – Configure AOP Declaratively
An example using the aop namespace
The MyDependency Class: public class MyDependency { public void foo(int intValue) { System.out.println("foo(int): " + intValue); } public void bar() { System.out.println("bar()"); } }
The MyBean Class: public class MyBean { private MyDependency dep; public void execute() { dep.foo(100); dep.foo(101); dep.bar(); } public void setDep(MyDependency dep) { this.dep = dep; } }
© SkywideSoft Technology Limited 67
Spring AOP – Configure AOP Declaratively
An example using the aop namespace
The MyAdvice Class:
import org.aspectj.lang.JoinPoint; public class MyAdvice { public void simpleBeforeAdvice(JoinPoint joinPoint) { System.out.println("Executing: " + joinPoint.getSignature().getDeclaringTypeName() + " " + joinPoint.getSignature().getName()); } }
© SkywideSoft Technology Limited 68
Spring AOP – Configure AOP Declaratively
An example using the aop namespace
Spring ApplicationContext Configuration File:
… <aop:config> <aop:pointcut id="fooExecution“ expression="execution(* com.apress.prospring3.ch7..foo*(int))"/> <aop:aspect ref="advice"> <aop:before pointcut-ref="fooExecution“ method="simpleBeforeAdvice"/> </aop:aspect> </aop:config> <bean id="advice" class="com.apress.prospring3.ch7.aopns.MyAdvice"/> <bean id="myDependency“ class="com.apress.prospring3.ch7.aopns.MyDependency"/> <bean id="myBean" class="com.apress.prospring3.ch7.aopns.MyBean"> <property name="dep" ref="myDependency"/> </bean> …
© SkywideSoft Technology Limited 69
Spring AOP – Configure AOP Declaratively
An example using the aop namespace
Testing program:
public class AopNamespaceExample { public static void main(String[] args) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load("classpath:aopns.xml"); ctx.refresh(); MyBean myBean = (MyBean) ctx.getBean("myBean"); myBean.execute(); } }
Output: Executing: com.apress.prospring3.ch7.aopns.MyDependency foo foo(int): 100 Executing: com.apress.prospring3.ch7.aopns.MyDependency foo foo(int): 101 bar()
© SkywideSoft Technology Limited 70
Spring AOP – Using @AspectJ Style Annotations
@Component("myDependency") public class MyDependency { public void foo(int intValue) { System.out.println("foo(int): " + intValue); } public void bar() { System.out.println("bar()"); } }
The MyBean Class: @Component("myBean") public class MyBean { @Autowired private MyDependency myDependency; public void execute() { myDependency.foo(100); myDependency.foo(101); myDependency.bar(); } }
The MyDependency Class:
© SkywideSoft Technology Limited 71
Spring AOP – Using @AspectJ Style Annotations
The MyAdvice Class: @Component @Aspect public class MyAdvice { @Pointcut("execution(* com.apress.prospring3.ch7..foo*(int)) && args(intValue)") public void fooExecution(int intValue) { } @Pointcut("bean(myDependency*)") public void inMyDependency() { } @Before("fooExecution(intValue) && inMyDependency()") public void simpleBeforeAdvice(JoinPoint joinPoint, int intValue) { // Execute only when intValue is not 100 if (intValue != 100) { System.out.println("Executing: " + joinPoint.getSignature().getDeclaringTypeName() + " " + joinPoint.getSignature().getName() + " argument: " + intValue); } } @Around("fooExecution(intValue) && inMyDependency()") public Object simpleAroundAdvice(ProceedingJoinPoint pjp, int intValue) throws Throwable { …
© SkywideSoft Technology Limited 72
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 73
Spring Persistence – Hibernate and JPA
A simple contact application
Data Model:
© SkywideSoft Technology Limited 74
Spring Persistence – Hibernate and JPA
A simple contact application
Domain Object Model:
© SkywideSoft Technology Limited 75
Spring Persistence – Hibernate and JPA
A simple contact application
The Contact class with JPA mapping annotations:
@Entity @Table(name = "contact") public class Contact implements Serializable { private Long id; private int version; private String firstName; private String lastName; private Date birthDate; @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "ID") public Long getId() { return this.id; } @Version @Column(name = "VERSION") public int getVersion() { return this.version; }
© SkywideSoft Technology Limited 76
Spring Persistence – Hibernate and JPA
@Column(name = "FIRST_NAME") public String getFirstName() { return this.firstName; } @Column(name = "LAST_NAME") public String getLastName() { return this.lastName; } @Temporal(TemporalType.DATE) @Column(name = "BIRTH_DATE") public Date getBirthDate() { return this.birthDate; } … }
© SkywideSoft Technology Limited 77
Spring Persistence – Hibernate and JPA
A simple contact application
The ContactTelDetail class with JPA mapping annotations:
@Entity @Table(name = "contact_tel_detail") public class ContactTelDetail implements Serializable { private Long id; private int version; private String telType; private String telNumber; … @Column(name = "TEL_TYPE") public String getTelType() { return this.telType; } @Column(name = "TEL_NUMBER") public String getTelNumber() { return this.telNumber; } }
© SkywideSoft Technology Limited 78
Spring Persistence – Hibernate and JPA
A simple contact application
The Hobby class with JPA mapping annotations:
@Entity @Table(name = "hobby") public class Hobby implements Serializable { private String hobbyId; @Id @Column(name = "HOBBY_ID") public String getHobbyId() { return this.hobbyId; } public void setHobbyId(String hobbyId) { this.hobbyId = hobbyId; } public String toString() { return "Hobby :" + getHobbyId(); } }
© SkywideSoft Technology Limited 79
Spring Persistence – Hibernate and JPA
A simple contact application
One-to-many mapping between Contact and ContactTelDetail class:
@Entity @Table(name = "contact") public class Contact implements Serializable { // Other code omitted private Set<ContactTelDetail> contactTelDetails = new HashSet<ContactTelDetail>(); @OneToMany(mappedBy = "contact", cascade=CascadeType.ALL, orphanRemoval=true) public Set<ContactTelDetail> getContactTelDetails() { return this.contactTelDetails; } }
@Entity @Table(name = "contact_tel_detail") public class ContactTelDetail implements Serializable { // Other code omitted private Contact contact; @ManyToOne @JoinColumn(name = "CONTACT_ID") public Contact getContact() { return this.contact; } }
© SkywideSoft Technology Limited 80
Spring Persistence – Hibernate and JPA
A simple contact application
Many-to-many mapping between Contact and Hobby class:
@Entity @Table(name = "contact") public class Contact implements Serializable { // Rest of code omitted private Set<Hobby> hobbies = new HashSet<Hobby>(); @ManyToMany @JoinTable(name = "contact_hobby_detail", joinColumns = @JoinColumn(name = "CONTACT_ID"), inverseJoinColumns = @JoinColumn( name = "HOBBY_ID")) public Set<Hobby> getHobbies() { return this.hobbies; } }
@Entity @Table(name = "hobby") public class Hobby implements Serializable { // Other code omitted private Set<Contact> contacts = new HashSet<Contact>(); @ManyToMany @JoinTable(name = "contact_hobby_detail", joinColumns = @JoinColumn(name = "HOBBY_ID"), inverseJoinColumns = @JoinColumn( name = "CONTACT_ID")) public Set<Contact> getContacts() { return this.contacts; } }
© SkywideSoft Technology Limited 81
Spring Persistence – Hibernate and JPA
Query data using Java Persistence Query Language
Define named queries for the Contact domain class:
@Table(name = "contact") @NamedQueries({ @NamedQuery(name="Contact.findAll", query="select c from Contact c"), @NamedQuery(name="Contact.findById", query="select distinct c from Contact c left join fetch c.contactTelDetails t left join fetch c.hobbies h where c.id = :id"), @NamedQuery(name="Contact.findAllWithDetail", query="select distinct c from Contact c left join fetch c.contactTelDetails t left join fetch c.hobbies h") }) public class Contact implements Serializable { // Other code omitted }
© SkywideSoft Technology Limited 82
Spring Persistence – Hibernate and JPA
Query data using Java Persistence Query Language
The ContactService interface:
public interface ContactService { // Find all contacts public List<Contact> findAll(); // Find all contacts with telephone and hobbies public List<Contact> findAllWithDetail(); // Find a contact with details by id public Contact findById(Long id); // Insert or update a contact public Contact save(Contact contact); // Delete a contact public void delete(Contact contact); }
© SkywideSoft Technology Limited 83
Spring Persistence – Hibernate and JPA
Query data using Java Persistence Query Language
Implementing the findAll() method:
// Import statements omitted @Service("jpaContactService") @Repository @Transactional public class ContactServiceImpl implements ContactService { @PersistenceContext private EntityManager em; // Other code omitted @Transactional(readOnly=true) public List<Contact> findAll() { List<Contact> contacts = em.createNamedQuery("Contact.findAll", Contact.class).getResultList(); return contacts; } }
© SkywideSoft Technology Limited 84
Spring Persistence – Hibernate and JPA
Insert/update data with JPA
Implementing the save() method:
// Import statements omitted @Service("jpaContactService") @Repository @Transactional public class ContactServiceImpl implements ContactService { // Other code omitted public Contact save(Contact contact) { if (contact.getId() == null) { // Insert Contact log.info("Inserting new contact"); em.persist(contact); } else { // Update Contact em.merge(contact); log.info("Updating existing contact"); } log.info("Contact saved with id: " + contact.getId()); return contact; } }
© SkywideSoft Technology Limited 85
Spring Persistence – Hibernate and JPA
Delete data with JPA
Implementing the delete() method:
// Import statements omitted @Service("jpaContactService") @Repository @Transactional public class ContactServiceImpl implements ContactService { private Log log = LogFactory.getLog(ContactServiceImpl.class); // Other code omitted public void delete(Contact contact) { Contact mergedContact = em.merge(contact); em.remove(mergedContact); log.info("Contact with id: " + contact.getId() + " deleted successfully"); } }
© SkywideSoft Technology Limited 86
Spring Persistence
Spring Framework integrates with the following data access frameworks:
• JDBC
• Hibernate 3/4
• iBatis
• JDO (Java Data Objects)
• JPA
© SkywideSoft Technology Limited 87
Spring Persistence – Spring Data
Spring Data – Modern Data Access for Enterprise Java
Category Sub-Project Description
Common Infrastructure
Commons Provides shared infrastructure for use across various data access projects.
RDBMS JPA Spring Data JPA - Simplifies the development of creating a JPA-based data access layer
JDBC Extensions Support for Oracle RAC, Advanced Queuing, and Advanced datatypes. Support for using QueryDSL with JdbcTemplate.
Big Data Apache Hadoop The Apache Hadoop project is an open-source implementation of frameworks for reliable, scalable, distributed computing and data storage.
Data Grid GemFire VMware vFabric GemFire is a distributed data management platform providing dynamic scalability, high performance, and database-like persistence. It blends advanced techniques like replication, partitioning, data-aware routing, and continuous querying.
HTTP REST Spring Data REST - Perform CRUD operations of your persistence model using HTTP and Spring Data Repositories.
Key Value Store Redis Redis is an open source, advanced key-value store.
Document Store MongoDB MongoDB is a scalable, high-performance, open source, document-oriented database.
© SkywideSoft Technology Limited 88
Spring Persistence – Spring Data JPA
Main Features:
• Sophisticated support to build repositories based on Spring and JPA
• Support for QueryDSL predicates and thus type-safe JPA queries
• Transparent auditing of domain class
• Pagination support, dynamic query execution, ability to integrate custom data access code
• Validation of @Query annotated queries at bootstrap time
• Support for XML based entity mapping
© SkywideSoft Technology Limited 89
Spring Persistence – Spring Data JPA
Spring Data JPA Repository Abstraction
The CrudRepository interface:
package org.springframework.data.repository; import java.io.Serializable; @NoRepositoryBean public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> { T save(T entity); Iterable<T> save(Iterable<? extends T> entities); T findOne(ID id); boolean exists(ID id); Iterable<T> findAll(); long count(); void delete(ID id); void delete(T entity); void delete(Iterable<? extends T> entities); void deleteAll(); }
© SkywideSoft Technology Limited 90
Spring Persistence – Spring Data JPA
Spring Data JPA Repository Abstraction
The revised ContactService interface:
public interface ContactService { // Find all contacts public List<Contact> findAll(); // Find contacts by first name public List<Contact> findByFirstName(String firstName); // Find contacts by first name and last name public List<Contact> findByFirstNameAndLastName(String firstName, String lastName); }
© SkywideSoft Technology Limited 91
Spring Persistence – Spring Data JPA
Spring Data JPA Repository Abstraction
Implementing the revised ContactRepository interface:
public interface ContactRepository extends CrudRepository<Contact, Long> { public List<Contact> findByFirstName(String firstName); public List<Contact> findByFirstNameAndLastName(String firstName, String lastName); }
<jpa:repositories base-package="com.apress.prospring3.ch10.repository" entity-manager-factory-ref="emf" transaction-manager-ref="transactionManager"/>
Spring ApplicationContext Configuration:
© SkywideSoft Technology Limited 92
Spring Persistence – Spring Data JPA
Spring Data JPA Repository Abstraction
Implementing the ContactService interface with Spring Data JPA:
public class ContactServiceImpl implements ContactService { @Autowired private ContactRepository contactRepository; @Transactional(readOnly=true) public List<Contact> findAll() { return Lists.newArrayList(contactRepository.findAll()); } @Transactional(readOnly=true) public List<Contact> findByFirstName(String firstName) { return contactRepository.findByFirstName(firstName); } @Transactional(readOnly=true) public List<Contact> findByFirstNameAndLastName(String firstName, String lastName) { return contactRepository.findByFirstNameAndLastName(firstName, lastName); } }
© SkywideSoft Technology Limited 93
Spring Persistence – Spring Data JPA
Spring Data JPA Repository Abstraction
Benefits:
• Don’t need to prepare a named query
• Don’t need to call the EntityManager.createQuery() method
• Defining custom queries with the @Query annotation
• The Specification feature
© SkywideSoft Technology Limited 94
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 95
Spring Expression Language (SpEL)
What is SpEL?
• A powerful expression language
• Much like OGNL, MVEL, JBoss EL, JSP EL, etc.
• Supports querying and manipulating an object graph at run time
• Can be used across all Spring projects (Spring Framework, Batch, Integration, Security, Webflow, etc.)
• Can be used outside of Spring
© SkywideSoft Technology Limited 96
Spring Expression Language (SpEL)
Features
• expressions
• accessing properties, arrays, etc.
• assignment
• method invocation
• collection selection & projection
• etc.
© SkywideSoft Technology Limited 97
Spring Expression Language (SpEL)
SpEL Fundamentals
• ExpressionParser
• Expression
getValue
setValue
• EvaluationContext
root
setVariable
propertyAccessor
© SkywideSoft Technology Limited 98
Spring Expression Language (SpEL)
Expression Access
• Programming
parser.parseExpression(“expression for root”)
parser.parseExpression(“#expression for variable”)
• Configuration XML / @Value
#{expression}
• Custom Template
Parser.parseExpression(“it is #{expression}”)
© SkywideSoft Technology Limited 99
Programming SpEL
Expression Evaluation – A simple example
Evaluate a simple string expression:
ExpressionParser parser = new SpelExpressionParser(); // Simple expression evaluation Expression exp = parser.parseExpression("'Hello World'"); String message = exp.getValue(String.class); System.out.println("Message: " + message);
Chaining of expression evaluation and get the result:
ExpressionParser parser = new SpelExpressionParser(); // Simple expression evaluation String message = parser.parseExpression("'Hello World'").getValue(String.class)
© SkywideSoft Technology Limited 100
Programming SpEL
Expression Evaluation – A simple example
Literal expressions:
ExpressionParser parser = new SpelExpressionParser(); double value = parser.parseExpression(“6.0221415E+23”).getValue(Double.class); int value = parser.parseExpression(“0x7FFFFFFF”).getValue(Integer.class); Date someDate = parser.parseExpression(“’2012/07/09’”).getValue(Date.class); boolean result = parser.parseExpression(“true”).getValue(); Object someObj = parser.parseExpression(“null”).getValue();
© SkywideSoft Technology Limited 101
Programming SpEL
Evaluation Expressions Against an Object Instance Expression is evaluated against a specific object instance (called the root object) 2 options
Use EvaluationContext (root object is the same for every invocation) Pass the object instance to getValue() method
Use EvaluationContext:
ExpressionParser parser = new SpelExpressionParser(); Contact contact = new Contact("Scott", "Tiger", 30); // Contact(firstName, lastName, age) // SpEL against object with EvaluationContext Expression exp = parser.parseExpression("firstName"); EvaluationContext context = new StandardEvaluationContext(contact); // contact is the root object String firstName = exp.getValue(context, String.class);
Calling getValue() and pass in the root object:
ExpressionParser parser = new SpelExpressionParser(); // SpEL against object by calling getValue() contact.setFirstName("Clarence"); firstName = exp.getValue(contact, String.class); // pass in contact as the root object
© SkywideSoft Technology Limited 102
Programming SpEL
Expression Support for Bean Definitions
XML Configuration:
<bean id="xmlConfig" class="com.fil.training.spel.xml.XmlConfig"> <property name="operatingSystem" value="#{systemProperties['os.name']}"></property> <property name="javaVersion" value="#{systemProperties['java.vm.version']}"></property> <property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"></property> </bean> <bean id="xmlBean" class="com.fil.training.spel.xml.XmlBean"> <property name="luckyNumber" value="#{xmlConfig.randomNumber + 1}"/> </bean>
© SkywideSoft Technology Limited 103
Programming SpEL
Expression Support for Bean Definitions
Annotation Configuration
@Component("applicationConfig") public class ApplicationConfig { @Value("#{systemProperties['user.home']}") private String baseFolder; … }
ApplicationConfig.java:
@Component("batchJobConfig") public class BatchJobConfig { @Value("#{systemProperties['file.separator'] + 'batchjob'}") private String batchJobFolder; … }
BatchJobConfig.java:
© SkywideSoft Technology Limited 104
Programming SpEL
Expression Support for Bean Definitions
Annotation Configuration (cont.)
@Component("sampleBatchJob") public class SampleBatchJob { @Value("#{applicationConfig.baseFolder + batchJobConfig.batchJobFolder + systemProperties['file.separator'] + 'simplejob'}") private String inputFolder; … }
SampleBatchJob.java:
Result of sample batch job input folder (example): /usr/home/user/batchjob/simplejob
© SkywideSoft Technology Limited 105
Programming SpEL
Language Highlights
Object Properties:
#{person.name}
#{person.Name}
#{person.getName()}
© SkywideSoft Technology Limited 106
Programming SpEL
Language Highlights
Collections:
#{list[0]}
#{list[0].name}
#{map[‘key’]}
© SkywideSoft Technology Limited 107
Programming SpEL
Language Highlights
Methods:
#{‘Some Text’.substring(0,2)}
#{‘Some Text’.startsWith(‘text’)}
#{“variable.toString()”}
© SkywideSoft Technology Limited 108
Programming SpEL
Language Highlights
Relational Operators:
#{5 == 5} or #{5 eq 5}
#{‘black’ > ‘block’} or #{‘black’ gt ‘block’}
#{‘text’ instanceof T(int)}
#{‘5.00’ matches ‘^-?\\d+(\\.\\d{2})?$’}
© SkywideSoft Technology Limited 109
Programming SpEL
Language Highlights
Arithmetic Operators:
#{5 + 5}
#{(5 + 5) * 2}
#{17 / 5 % 3}
#{‘Hello’ + ‘ ‘ + ‘world’}
© SkywideSoft Technology Limited 110
Programming SpEL
Language Highlights
Logical Operators:
#{true or false}
#{true}
#{not isUserInGroup(‘admin’)}
© SkywideSoft Technology Limited 111
Programming SpEL
Language Highlights
Type Operators:
#{T(java.util.Date)}
#{T(String)}
#{T(int)}
Accessing static class members
#{T(Math).PI}
#{T(Math).random()}
© SkywideSoft Technology Limited 112
Programming SpEL
Language Highlights
instanceof:
#{‘text’ instanceof T(String)}
#{27 instanceof T(Integer)}
#{false instanceof T(Boolean)}
© SkywideSoft Technology Limited 113
Programming SpEL
Language Highlights
Constructor:
#{new org.training.spel.Contact(‘Scott’,’Tiger’,30)}
#{list.add(new org.training.spel.Person())}
© SkywideSoft Technology Limited 114
Programming SpEL
Language Highlights
If-then-else:
#{person.age>50 ? ’Old’ : ’Young’}
#{person.name ?: ‘N/A’}
© SkywideSoft Technology Limited 115
Programming SpEL
Language Highlights
Safe navigation:
#{address.city?.name}
#{person.name?.length()}
© SkywideSoft Technology Limited 116
Programming SpEL
Language Highlights
Collection selection:
Select all
#{list.?[age>20]}
#{list.?[name.startsWith(‘D’)]}
Select first
#{list.^[age>20]}
Select last
#{list.$[getAge()>20]}
© SkywideSoft Technology Limited 117
Programming SpEL
Language Highlights
Collection projection:
Select the names of all elements
#{list.![name]}
Select the names’ length of all elements
#{list.![name.length()]}
© SkywideSoft Technology Limited 118
Programming SpEL
More Advance Features
Register custom functions in EvaluationContext
Expression templating
Access to Spring context
© SkywideSoft Technology Limited 119
Programming SpEL
Summary
One of the main new feature in Spring 3
Works with all Spring projects
Can be used outside of Spring
Very useful for wiring bean properties
Will be mostly used in XML and Annotations based beans definitions
© SkywideSoft Technology Limited 120
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 121
Spring MVC
Main Features
Support MVC pattern for Web Application
Native supports for i18n, themes, content negotiation
Comprehensive support of RESTful-WS
Support JSR-303 Bean Validation API
Integrates with popular web frameworks and view technologies
Apache Struts
Apache Tiles
JSF
JavaScript
© SkywideSoft Technology Limited 122
Spring MVC
Introducing MVC
Model
A model represents the business data as well as the “state” of the application within the context of the user. For example, in an e-commerce web site, the model will include the user profile information, shopping cart data, and order data if users purchase goods on the site.
View
This presents the data to the user in the desired format, supports interaction with users, and supports client-side validation, i18n, styles, and so on.
Controller
The controller handles requests for actions performed by users in the frontend, interacting with the service layer, updating the model, and directing users to the appropriate view based on the result of execution.
© SkywideSoft Technology Limited 123
Spring MVC
The MVC Pattern
© SkywideSoft Technology Limited 124
Spring MVC
Spring MVC WebApplicationContext Hierarchy
© SkywideSoft Technology Limited 125
Spring MVC
Spring MVC Request Handling Life-cycle
© SkywideSoft Technology Limited 126
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 127
SpringBlog
Main Features
Allow users to view and post blog entries
Allow users to post comments on blog entries
Allow users to upload attachment for blog entries
Support AOP for filtering bad words
Support multiple languages (English, Chinese)
Support multiple databases (H2, MySQL)
Support multiple data access frameworks (Hibernate, MyBatis)
Provides RESTful-WS for retrieving blog entries
Supports batch upload of blog entries from XML files
Presentation layer
Built with Spring MVC, JSPX and jQuery JavaScript library
© SkywideSoft Technology Limited 128
SpringBlog
Application Layered Architecture
© SkywideSoft Technology Limited 129
SpringBlog
Sample Screen – Viewing Blog Post Entries:
© SkywideSoft Technology Limited 130
SpringBlog
Sample Screen – Posting Blog Post Entries:
© SkywideSoft Technology Limited 131
SpringBlog
Obtaining the source code
Download from the Pro Spring 3 book page (free)
http://www.apress.com/downloadable/download/sample/sample_id/1282/
Checkout from GitHub
https://github.com/prospring3/springblog
Need Help!!! Visit Pro Spring 3 discussion forum
http://www.skywidesoft.com/index.php/discussions/index/pro-spring-3
© SkywideSoft Technology Limited 132
The Power of Enterprise Java Frameworks
© SkywideSoft Technology Limited 133
Conclusion
Java Enterprise Framework
Provides a skeleton for building enterprise applications in Java
Provides out-of-the-box support of critical technologies
DI, AOP, Data Access, Web, RESTful-WS, etc.
Tightly integrates with JEE standards
JPA, JTA, Bean Validation, JSF, and many others
© SkywideSoft Technology Limited 134
Conclusion
Spring Framework
The most popular Java Enterprise Application framework
Supports/compatible with all major JEE standards
A large number of projects for supporting specific needs:
Spring Security
Spring Batch
Spring Integration
Spring Data
Spring WebFlow
Spring Mobile
Over 2 million developers are using Spring
Excellent documentation and vibrant community
© SkywideSoft Technology Limited 135
The Power of Enterprise Java Frameworks