Mais conteúdo relacionado Semelhante a The Power of Enterprise Java Frameworks (20) The Power of Enterprise Java Frameworks1. The Power of Enterprise Java Frameworks
• Clarence Ho
• Independent Consultant, Author, Java EE Architect
• http://www.skywidesoft.com
• clarence@skywidesoft.com
• Presentation can be downloaded from:
• http://www.skywidesoft.com/index.php/seminar
1
© SkywideSoft Technology Limited
2. Outline
• What is an Enterprise Java Framework?
• Overview of popular Enterprise Java Frameworks
• The most popular Enterprise Java framework -
Spring Framework
• Resources
• Conclusion
• Q&A
2
© SkywideSoft Technology Limited
3. The Power of Enterprise Java Frameworks
3
© SkywideSoft Technology Limited
4. What is a software framework?
• 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.
Source: Wikipedia
4
© SkywideSoft Technology Limited
5. What is a software framework? (cont.)
Frameworks contain key distinguishing features that separate them from
normal libraries:
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.
Source: Wikipedia
5
© SkywideSoft Technology Limited
6. What is an application framework?
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.
Source: Wikipedia
6
© 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 …
7
© 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
8
© SkywideSoft Technology Limited
9. The Power of Enterprise Java Frameworks
9
© SkywideSoft Technology Limited
10. IOC and DI – Main Purpose
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
Source: Pro Spring 3
10
© SkywideSoft Technology Limited
11. Type of IOC – Dependency Pull
Examples:
- EJB (prior to version 2.1)
- Spring (BeanFactory or ApplicationContext)
Source: Pro Spring 3
11
© SkywideSoft Technology Limited
12. Type of IOC – Dependency Pull (cont.)
Dependency Pull in Spring:
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();
}
Source: Pro Spring 3
12
© SkywideSoft Technology Limited
13. Type of IOC – Contextual Dependency Lookup
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.
Source: Pro Spring 3
13
© SkywideSoft Technology Limited
14. Type of IOC – CDL (cont.)
An interface for dependent object:
public interface ManagedComponent {
public void performLookup(Container container);
}
A container interface:
public interface Container {
public Object getDependency(String key);
}
Obtaining dependency when container is ready:
package com.apress.prospring3.ch4;
public class ContextualizedDependencyLookup implements ManagedComponent {
private Dependency dependency;
public void performLookup(Container container) {
this.dependency = (Dependency) container.getDependency("myDependency");
}
}
Source: Pro Spring 3
14
© SkywideSoft Technology Limited
15. Type of IOC – Dependency Injection
Spring’s Dependency Injection Mechanism:
Constructor Injection: Setter Injection:
public class ConstructorInjection { public class SetterInjection {
private Dependency dependency; private Dependency dependency;
public ConstructorInjection(Dependency dependency) { public void setDependency(Dependency dependency) {
this.dependency = dependency; this.dependency = dependency;
} }
} }
Source: Pro Spring 3
15
© SkywideSoft Technology Limited
16. The Power of Enterprise Java Frameworks
16
© SkywideSoft Technology Limited
17. JEE 6
• A collection of JCP (Java Community Process) standards
• Implemented by all JEE compliant application servers
Oracle WebLogic 12c
Oracle Glassfish 3.1
IBM WebSphere 8.5
JBoss Application
Server 7.1
Apache TomEE 1.0.0
Source: Pro Spring 3
17
© SkywideSoft Technology Limited
18. JEE 6 – Features/API Overview
Source: JavaOne Presentation by IBM
18
© 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
19
© SkywideSoft Technology Limited
20. Jboss Seam Framework – Features/API Overview
Hibernate
RichFaces
Source: JavaOne Presentation by IBM
20
© 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
21
© 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
22
© SkywideSoft Technology Limited
23. Spring Framework – Features/API Overview
Source: JavaOne Presentation by IBM
23
© SkywideSoft Technology Limited
24. JEE vs Spring – Features/API Overview
* Similar patterns for validation, remoting, security, scheduling, XML binding, JMX, JCA, JavaMail, caching
* Spring also support EJB 3.1, but not CDI
Source: JavaOne Presentation by IBM
24
© SkywideSoft Technology Limited
25. The Power of Enterprise Java Frameworks
25
© 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 Spring Data
platform using JDBC and object-relational mapping tools and with projects
NoSQL databases
Transaction Unifies several transaction management APIs (JDBC, JPA, JTA, etc.) and
Management coordinates transactions for Java objects.
Model-view- An HTTP- and servlet-based framework providing hooks for extension
controller and customization for web applications and RESTful Web Services.
Authentication Configurable security processes that support a range of standards, Spring
& Authorization protocols, tools and practices via the Spring Security sub-project Security
Remote Configurative exposure and management of Java objects for local or
Management 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
26 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 3.0
(Spring JavaConfig was merged into the core Spring
Framework since 3.0).
Embedded JDBC Embedded database support (by using the <jdbc:embedded- 3.1
DataSource database id="dataSource" type="H2"> tag)
Validation with Type Spring 3 introduce a new type conversion and formatting 3.0
Conversion and Formatting system, and support of JSR303 Bean Validation API.
Persistence with Spring Spring Data JPA’s Repository abstraction greatly simplifies the 3.0
Data JPA development of persistence layer with JPA.
Spring MVC Improved support of RESTful-WS. 3.1
Spring Expression Language A powerful expression language that supports querying and 3.0
manipulating an object graph at run time.
Profiles A profile instructs Spring to configure only the 3.1
ApplicationContext that was defined when the specified
profile was active
Cache Abstraction A caching abstraction layer that allows consistent use of 3.1
various caching solutions with minimal impact on the code.
TaskScheduler Abstraction Provides a simple way to schedule tasks and supports most 3.0
typical requirements.
27
© SkywideSoft Technology Limited
28. Other Useful Spring Projects
Project Description Version
Spring Security Configurable security processes that support a range of standards, 3.1.2
protocols, tools and practices
Spring Data An umbrella project includes many modules that simplifies the 1.X
development of persistence layer with various data sources (e.g. JPA,
NoSQL, JDBC, Hadoop, etc.)
Spring Batch Provides a standard template and framework for implementing and 2.1.8
executing various kinds of batch jobs in an enterprise environment.
Spring Integration Provides an excellent integration environment for enterprise 2.1.3
applications.
Spring WebFlow Building on top of Spring MVC’s foundation, Spring Web Flow was 2.3.1
designed to provide advanced support for organizing the flows inside
a web application.
Spring Mobile An extension to Spring MVC that aims to simplify the development of 1.0.0
mobile web applications.
Spring Roo A rapid application development solution for Spring-based enterprise 1.2.2
applications
SpringSource Tool An IDE tools with Eclipse and Spring IDE bundled, together witn 3.0.0
Suite numerous tools for developing Spring applications.
28
© SkywideSoft Technology Limited
29. The Power of Enterprise Java Frameworks
29
© 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
30
© SkywideSoft Technology Limited
31. The Power of Enterprise Java Frameworks
31
© SkywideSoft Technology Limited
32. Spring Beans Configuration
• Basic Configuration (XML and Annotations)
• Beans Life-cycle
• Configuration Using Java Classes
32
© SkywideSoft Technology Limited
33. Basic Configuration (XML and Annotations)
A simple interface and implementation.
public interface MessageProvider {
public String getMessage();
}
public class HelloWorldMessageProvider implements MessageProvider {
public String getMessage() {
return "Hello World!";
}
}
33
© SkywideSoft Technology Limited
34. Basic Configuration (XML and Annotations)
Interface and implementation of a dependent object.
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;
}
}
34
© SkywideSoft Technology Limited
35. Basic Configuration (XML and Annotations)
XML Configuration of Spring ApplicationContext.
<?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>
35
© SkywideSoft Technology Limited
36. Basic Configuration (XML and Annotations)
Setter and Constructor Injection.
<!-- 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"/>
36
© SkywideSoft Technology Limited
37. Basic Configuration (XML and Annotations)
Annotation Configuration of Spring ApplicationContext.
<?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>
37
© SkywideSoft Technology Limited
38. Basic Configuration (XML and Annotations)
Setter Injection with Annotations.
@Service("messageProvider")
public class HelloWorldMessageProvider implements MessageProvider {
@Service("messageRenderer")
public class StandardOutMessageRenderer implements MessageRenderer {
…
@Autowired
public void setMessageProvider(MessageProvider provider) {
this.messageProvider = provider;
}
…
}
38
© SkywideSoft Technology Limited
39. Basic Configuration (XML and Annotations)
Constructor Injection with Annotations.
@Service("messageProvider")
public class HelloWorldMessageProvider implements MessageProvider {
@Service("messageRenderer")
public class StandardOutMessageRenderer implements MessageRenderer {
…
@Autowired
public StandardOutMessageRenderer(MessageProvider provider) {
this.messageProvider = provider;
}
…
}
39
© SkywideSoft Technology Limited
41. Configuration Using Java Classes
A simple XML configuration.
<?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>
41
© SkywideSoft Technology Limited
42. Configuration Using Java Classes
Bootstrap Spring ApplicationContext using XML configuration.
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();
}
}
42
© SkywideSoft Technology Limited
43. Configuration Using Java Classes
A simple Java configuration class.
@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;
}
}
43
© SkywideSoft Technology Limited
44. Configuration Using Java Classes
Bootstrap Spring ApplicationContext 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();
}
}
44
© SkywideSoft Technology Limited
45. Configuration Using Java Classes
More Java configurations.
@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"));
}
45
© SkywideSoft Technology Limited
46. Configuration Using Java Classes
More Java configurations.
// 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;
}
}
46
© SkywideSoft Technology Limited
47. The Power of Enterprise Java Frameworks
47
© 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
48
© SkywideSoft Technology Limited
49. Define Beans for Various Profiles
Example: a food provider for kindergarten and high school.
The Food class:
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;
}
}
49
© SkywideSoft Technology Limited
50. Define Beans for Various Profiles
Example: a food provider for kindergarten and high school.
The FoodProviderService interface:
public interface FoodProviderService {
public List<Food> provideLunchSet();
}
50
© SkywideSoft Technology Limited
51. Define Beans for Various Profiles
Example: a food provider for kindergarten and high school.
The FoodProviderServiceImpl class for kindergarten profile:
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;
}
}
51
© SkywideSoft Technology Limited
52. Define Beans for Various Profiles
Example: a food provider for kindergarten and high school.
The FoodProviderServiceImpl class for high school profile:
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;
}
}
52
© SkywideSoft Technology Limited
53. Define Beans for Various Profiles
Example: a food provider for kindergarten and high school.
The XML config file for kindergarten profile (kindergarten-config.xml):
<?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>
53
© SkywideSoft Technology Limited
54. Define Beans for Various Profiles
Example: a food provider for kindergarten and high school.
The XML config file for high school profile (highschool-config.xml):
<?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>
54
© SkywideSoft Technology Limited
55. Define Beans for Various Profiles
Example: a food provider for kindergarten and high school.
Testing program with kindergarten profile activated:
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());
}
}
}
Output:
Food: Milk
Food: Biscuits
55
© SkywideSoft Technology Limited
56. Define Beans for Various Profiles
Example: a food provider for kindergarten and high school.
Testing program with highschool profile activated:
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());
}
}
}
Output:
Food: Coke
Food: Hamburger
Food: French Fries
56
© 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>
…
59
© 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.
60
© SkywideSoft Technology Limited
61. The Power of Enterprise Java Frameworks
61
© 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
62
© 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.
63
© SkywideSoft Technology Limited
64. Spring AOP – Architecture
The core architecture of Spring AOP is based around proxies.
64
© 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.
65
© 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;
}
}
66
© 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());
}
}
67
© 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>
…
68
© 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()
69
© SkywideSoft Technology Limited
70. Spring AOP – Using @AspectJ Style Annotations
The MyDependency Class:
@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();
}
}
70
© 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 {
…
71
© SkywideSoft Technology Limited
72. The Power of Enterprise Java Frameworks
72
© SkywideSoft Technology Limited
73. Spring Persistence – Hibernate and JPA
A simple contact application
Data Model:
73
© SkywideSoft Technology Limited
74. Spring Persistence – Hibernate and JPA
A simple contact application
Domain Object Model:
74
© 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;
}
75
© 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;
}
…
}
76
© 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;
}
}
77
© 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();
}
}
78
© SkywideSoft Technology Limited
79. Spring Persistence – Hibernate and JPA
A simple contact application
One-to-many mapping between Contact and ContactTelDetail class:
@Entity @Entity
@Table(name = "contact") @Table(name = "contact_tel_detail")
public class Contact implements Serializable { public class ContactTelDetail implements Serializable {
// Other code omitted // Other code omitted
private Set<ContactTelDetail> contactTelDetails = private Contact contact;
new HashSet<ContactTelDetail>();
@ManyToOne
@OneToMany(mappedBy = "contact", @JoinColumn(name = "CONTACT_ID")
cascade=CascadeType.ALL, public Contact getContact() {
orphanRemoval=true) return this.contact;
public Set<ContactTelDetail> getContactTelDetails() { }
return this.contactTelDetails; }
}
}
79
© SkywideSoft Technology Limited
80. Spring Persistence – Hibernate and JPA
A simple contact application
Many-to-many mapping between Contact and Hobby class:
@Entity @Entity
@Table(name = "contact") @Table(name = "hobby")
public class Contact implements Serializable { public class Hobby implements Serializable {
// Rest of code omitted // Other code omitted
private Set<Hobby> hobbies = private Set<Contact> contacts =
new HashSet<Hobby>(); new HashSet<Contact>();
@ManyToMany @ManyToMany
@JoinTable(name = "contact_hobby_detail", @JoinTable(name = "contact_hobby_detail",
joinColumns = @JoinColumn(name = "CONTACT_ID"), joinColumns = @JoinColumn(name = "HOBBY_ID"),
inverseJoinColumns = @JoinColumn( inverseJoinColumns = @JoinColumn(
name = "HOBBY_ID")) name = "CONTACT_ID"))
public Set<Hobby> getHobbies() { public Set<Contact> getContacts() {
return this.hobbies; return this.contacts;
} }
} }
80
© 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
}
81
© 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);
}
82
© 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;
}
}
83
© 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;
}
}
84
© 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");
}
}
85
© 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
86
© SkywideSoft Technology Limited
87. Spring Persistence – Spring Data
Spring Data – Modern Data Access for Enterprise Java
Category Sub-Project Description
Common Commons Provides shared infrastructure for use across various data
Infrastructure 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.
87
© 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
88
© 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();
}
89
© 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);
}
90
© 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);
}
Spring ApplicationContext Configuration:
<jpa:repositories base-package="com.apress.prospring3.ch10.repository"
entity-manager-factory-ref="emf"
transaction-manager-ref="transactionManager"/>
91
© 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);
}
}
92
© 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
93
© SkywideSoft Technology Limited
94. The Power of Enterprise Java Frameworks
94
© 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
95
© SkywideSoft Technology Limited
96. Spring Expression Language (SpEL)
Features
• expressions
• accessing properties, arrays, etc.
• assignment
• method invocation
• collection selection & projection
• etc.
96
© SkywideSoft Technology Limited
97. Spring Expression Language (SpEL)
SpEL Fundamentals
• ExpressionParser
• Expression
getValue
setValue
• EvaluationContext
root
setVariable
propertyAccessor
97
© 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}”)
98
© 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)
99
© 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();
100
© 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
101
© 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>
102
© SkywideSoft Technology Limited
103. Programming SpEL
Expression Support for Bean Definitions
Annotation Configuration
ApplicationConfig.java:
@Component("applicationConfig")
public class ApplicationConfig {
@Value("#{systemProperties['user.home']}")
private String baseFolder;
…
}
BatchJobConfig.java:
@Component("batchJobConfig")
public class BatchJobConfig {
@Value("#{systemProperties['file.separator'] + 'batchjob'}")
private String batchJobFolder;
…
}
103
© SkywideSoft Technology Limited
104. Programming SpEL
Expression Support for Bean Definitions
Annotation Configuration (cont.)
SampleBatchJob.java:
@Component("sampleBatchJob")
public class SampleBatchJob {
@Value("#{applicationConfig.baseFolder + batchJobConfig.batchJobFolder +
systemProperties['file.separator'] + 'simplejob'}")
private String inputFolder;
…
}
Result of sample batch job input folder (example):
/usr/home/user/batchjob/simplejob
104
© SkywideSoft Technology Limited
105. Programming SpEL
Language Highlights
Object Properties:
#{person.name}
#{person.Name}
#{person.getName()}
105
© SkywideSoft Technology Limited
106. Programming SpEL
Language Highlights
Collections:
#{list[0]}
#{list[0].name}
#{map[‘key’]}
106
© SkywideSoft Technology Limited
107. Programming SpEL
Language Highlights
Methods:
#{‘Some Text’.substring(0,2)}
#{‘Some Text’.startsWith(‘text’)}
#{“variable.toString()”}
107
© 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})?$’}
108
© SkywideSoft Technology Limited
109. Programming SpEL
Language Highlights
Arithmetic Operators:
#{5 + 5}
#{(5 + 5) * 2}
#{17 / 5 % 3}
#{‘Hello’ + ‘ ‘ + ‘world’}
109
© SkywideSoft Technology Limited
110. Programming SpEL
Language Highlights
Logical Operators:
#{true or false}
#{true}
#{not isUserInGroup(‘admin’)}
110
© 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()}
111
© SkywideSoft Technology Limited
112. Programming SpEL
Language Highlights
instanceof:
#{‘text’ instanceof T(String)}
#{27 instanceof T(Integer)}
#{false instanceof T(Boolean)}
112
© SkywideSoft Technology Limited
113. Programming SpEL
Language Highlights
Constructor:
#{new org.training.spel.Contact(‘Scott’,’Tiger’,30)}
#{list.add(new org.training.spel.Person())}
113
© SkywideSoft Technology Limited
114. Programming SpEL
Language Highlights
If-then-else:
#{person.age>50 ? ’Old’ : ’Young’}
#{person.name ?: ‘N/A’}
114
© SkywideSoft Technology Limited
115. Programming SpEL
Language Highlights
Safe navigation:
#{address.city?.name}
#{person.name?.length()}
115
© 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]}
116
© 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()]}
117
© SkywideSoft Technology Limited
118. Programming SpEL
More Advance Features
Register custom functions in EvaluationContext
Expression templating
Access to Spring context
118
© 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
119
© SkywideSoft Technology Limited
120. The Power of Enterprise Java Frameworks
120
© 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
121
© 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.
122
© SkywideSoft Technology Limited
124. Spring MVC
Spring MVC WebApplicationContext Hierarchy
124
© SkywideSoft Technology Limited
125. Spring MVC
Spring MVC Request Handling Life-cycle
125
© SkywideSoft Technology Limited
126. The Power of Enterprise Java Frameworks
126
© 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
127
© 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/s
ample_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/p
ro-spring-3
131
© SkywideSoft Technology Limited
132. The Power of Enterprise Java Frameworks
132
© 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
133
© 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
134
© SkywideSoft Technology Limited
135. The Power of Enterprise Java Frameworks
135
© SkywideSoft Technology Limited