SlideShare a Scribd company logo
1 of 43
By : Sumit Gole & Sourabh Aggarwal
Date : 13 August 2015
SPRING 4
Spring Versions
Spring 4.0
Spring 4.2
Spring 3.0
Spring Modules?
Spring 3.0
(past stop)
●
Application configuration using Java.
●
Servlet 3.0 API support
●
Support for Java SE 7
●
@MVC additions
●
Declarative model validation
●
Embedded database support
●
Many more....
Spring 4.0
(Current Stop)
●
Fully support for Java8 features.
●
Java 6 <= (Spring) = Java 8
●
Removed depricated packages and methods.
●
Groovy Bean Definition DSL.
●
Core Container Improvements.
●
General Web Improvements.
●
WebSocket, SockJS, and STOMP Messaging.
●
Testing Improvements.
Java 8.0 Support
●
Use of lambda expressions.
●
In Java 8 a lambda expression can be used
anywhere a functional interface is passed into a
method.
Example:
●
public interface RowMapper<T>
●
{
●
T mapRow(ResultSet rs, int rowNum) throws
SQLException;
●
}
Java 8.0 Support
●
For example the Spring JdbcTemplate class
contains a method.
public <T> List<T> query(String sql, RowMapper<T>
rowMapper)
throws DataAccessException
●
Implementation:
jdbcTemplate.query("SELECT * from queries.products", (rs,
rowNum) -> { Integer id = rs.getInt("id");
String description = rs.getString("description");});
Java 8.0 Support
●
Time and Date API
●
Spring 4 updated the date conversion framework
(data to java object <--> Java object to data) to
support JDK 8.0 Time and Date APIs.
●
@RequestMapping("/date/{localDate}")
●
public String get(@DateTimeFormat(iso =
ISO.DATE) LocalDate localDate)
●
{
●
return localDate.toString();
●
}
●
Spring 4 support Java 8 but that does not imply the
third party frameworks like Hibernate or Jakson
would also support. So be carefull.....
Java 8.0 Support
●
Repeating Annotations
●
Spring 4 respected the repeating annotatiuon
convention intrduced by Java 8.
●
Example:
@PropertySource("classpath:/example1.properties")
@PropertySource("classpath:/example2.properties")
public class Application {
Java 8.0 Support
●
Checking for null references in methods is
always big pain....
●
Example:
public interface EmployeeRepository extends CrudRepository<Employee,
Long> {
/**
* returns the employee for the specified id or
* null if the value is not found
*/
public Employee findEmployeeById(String id);
}
Calling this method as:
Employee employee = employeeRepository.findEmployeeById(“123”);
employee.getName(); // get a null pointer exception
Java 8.0 Support
●
Magic of java.util.Optional
●
public interface EmployeeRepository extends
CrudRepository<Employee, Long> {
●
/**
●
* returns the employee for the specified id or
●
* null if the value is not found
●
*/
●
public Optional<Employee> findEmployeeById(String id);
●
}
Java 8.0 Support
●
Java.util.Optional force the programmer to put
null check before extracting the information.
●
How?
Optional<Employee> optional =
employeeRepository.findEmployeeById(“123”);
if(optional.isPresent()) {
Employee employee = optional.get();
employee.getName();
}
Java 8.0 Support
●
Spring 4.0 use java.util.Optional in following
ways:
●
Option 1:
●
Old way :
@Autowired(required=false)
OtherService otherService;
●
New way:
@Autowired
●
Optional<OtherService> otherService;
●
Option 2:
@RequestMapping(“/accounts/
{accountId}”,requestMethod=RequestMethod.POST)
void update(Optional<String> accountId, @RequestBody Account
account)
Java 8.0 Support
●
Auto mapping of Parameter name
●
Java 8 support preserve method arguments name
in compiled code so spring4 can extract the
argument name from compiled code.
●
What I mean?
@RequestMapping("/accounts/{id}")
public Account getAccount(@PathVariable("id") String id)
●
can be written as
@RequestMapping("/accounts/{id}")
public Account getAccount(@PathVariable String id)
Java 8.0 support
l
Hands on!!!!
l
Groovy Bean Definition DSL
●
@Configuration is empowered with Groovy Bean
Builder.
●
Spring 4.0 provides Groovy DSL to configur Spring
applications.
●
How it works?
<bean id="testBean" class="com.xebia.TestBeanImpl">
<property name="someProperty" value="42"/>
<property name="anotherProperty" value="blue"/>
</bean>
import my.company.MyBeanImpl
beans = {
myBean(MyBeanImpl) {
someProperty = 42
otherProperty = "blue"
}
}
l
Groovy Bean Definition DSL
●
Additionally it allows to configure Spring bean
defination properties.
●
How?
●
sessionFactory(ConfigurableLocalSessionFactoryBean) { bean ->
●
// Sets the initialization method to 'init'. [init-method]
●
bean.initMethod = 'init'
●
// Sets the destruction method to 'destroy'. [destroy-method]
●
bean.destroyMethod = 'destroy'
●
Spring + Groovy ---> More Strong and clean
implementation.
l
Groovy Bean Definition DSL
●
How both work together?
beans {
//
org.springframework.beans.factory.groovy.GroovyBe
anDefinitionReader
if (environment.activeProfiles.contains("prof1")) {
foo String, 'hello'
} else {
foo String, 'world'
}
}
●
In above code DSL uses GroovyBeanDefinitionReader to
interpret Groovy code.
Groovy Bean Definition DSL
●
If the bean defined in the previous code is placed in
the file config/contextWithProfiles.groovy the
following code can be used to get the value for String
foo.
Example:
ApplicationContext context = new
GenericGroovyApplicationContext("file:config/contextWithPro
files.groovy");
String foo = context.getBean("foo",String.class);
Groovy Bean Definition DSL
Hands on!!!!
l
Core Container Improvements.
●
Meta Annotations support
●
Defining custom annotations that combines many
spring annotations.
●
Example
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional
@Repository
@Scope("prototype")
@Transactional(propagation = Propagation.REQUIRES_NEW,
timeout = 30, isolation=Isolation.SERIALIZABLE)
public class OrderDaoImpl implements OrderDao {
.....}
●
Without writing any logic we have to repeat the above code in many
classes!!!!!
l
Core Container Improvements.
●
Spring 4 custom annotation
●
import org.springframework.context.annotation.Scope;
●
import org.springframework.stereotype.Repository;
●
import org.springframework.transaction.annotation.Isolation;
●
import org.springframework.transaction.annotation.Propagation;
●
import org.springframework.transaction.annotation.Transactional;
●
●
@Repository
●
@Scope("prototype")
●
@Transactional(propagation = Propagation.REQUIRES_NEW,
timeout = 30, isolation=Isolation.SERIALIZABLE)
●
public @interface MyDao {
●
}
l
Core Container Improvements.
●
Spring 4 custom annotation
How to use the custom annotation?
@MyDao
public class OrderDaoImpl implements OrderDao {
...
}
l
Core Container Improvements
Generic qualifiers
Java genric types can be used as implicit form of qualification.
How?
public class Dao<T> {
...
}
@Configuration
public class MyConfiguration {
@Bean
public Dao<Person> createPersonDao() {
return new Dao<Person>();
}
@Bean
public Dao<Organization> createOrganizationDao() {
return new Dao<Organization>();
}
}
Core Container Improvements
●
How to call?
@Autowired
private Dao<Person> dao;
●
Spring 4 container identify which bean to inject on the
bases of Java generics.
Core Container Improvements
●
Conditionally bean defination
●
Conditionally enable and disable bean defination or whole
configuration.
●
Spring 3.x
@Configuration @Configuration
@Profile("Linux") @Profile(“Window”)
public class LinuxConfiguration { public class
indowConfiguration{
@Bean @Bean
public EmailService emailerService() { public EmailService
emailerService(){
return new LinuxEmailService(); return new
WindowEmailService();
} }
} }
Core Container Improvements
@Conditional is a flexible annotation, is consulted by the
container before @Bean is registered.
How?
The Conditional interface method
@Override public boolean matches(ConditionContext
context, AnnotatedTypeMetadata metadata) is overridden.
context : provides access to the environment, class loader
and container.
metadata: metadata of the class being checked.
Core Container Improvements
● The previous example would be implemented as
public class LinuxCondition implements Condition{
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Linux"); }
}
public class WindowsCondition implements Condition{
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Windows");
}
}
Core Container Improvements
@Configuration
public class MyConfiguration {
@Bean(name="emailerService")
@Conditional(WindowsCondition.class)
public EmailService windowsEmailerService(){
return new WindowsEmailService();
}
@Bean(name="emailerService")
@Conditional(LinuxCondition.class)
public EmailService linuxEmailerService(){
return new LinuxEmailService();
}
}
Core Container Improvements
● @Order and Autowiring
– Beans can be orderly wired by adding the @Order annotation in the @Bean
implementations as follows
@Component
@Order(value=1)
public class Employee implements Person {
..
}
@Component
@Order(value=2)
public class Customer implements Person {
......
}
Using the
@Autowired
List<Person> people;
Results in
[com.intertech.Employee@a52728a, com.intertech.Customer@2addc751]
Java 8.0 support
Hands on!!!!
General Web Improvments
– New @RestController annotation with Spring MVC application provide
specific implementation for RestFull web services, removing
requirement to add @ResponseBody to each of your
@RequestMapping.
– Spring 3.x
@Controller public class SpringContentController
{
@Autowired UserDetails userDetails;
@RequestMapping(value="/springcontent",
method=RequestMethod.GET,produces={"application/xml", "application/json"})
@ResponseStatus(HttpStatus.OK)
public @ResponseBody UserDetails getUser() {
UserDetails userDetails = new UserDetails();
userDetails.setUserName("Krishna"); userDetails.setEmailId("krishna@gmail.com");
return userDetails;
}
General Web Improvments
With @RestController annotation
– @RestController public class SpringContentController
{
@Autowired UserDetails userDetails;
@RequestMapping(value="/springcontent",
method=RequestMethod.GET,produces={"application/xml",
"application/json"}) @ResponseStatus(HttpStatus.OK)
public UserDetails getUser()
{
UserDetails userDetails = new UserDetails();
userDetails.setUserName("Krishna");
userDetails.setEmailId("krishna@gmail.com"); return
userDetails;
}
General Web Improvments
– Jakson integration improvements.
– Filter the serialized object in the Http Response body with Jakson Serialization view.
– @JsonView annotation is used to filter the fields depending on the requirement. e.g. When getting the Collection in
Http response then pass only the summary and if single object is requested then return the full object.
– Example
public class View {
interface Summary {}
}
public class User {
@JsonView(View.Summary.class)
private Long id;
@JsonView(View.Summary.class)
private String firstname;
@JsonView(View.Summary.class)
private String lastname;
private String email;
private String address;
}
General Web Improvments
public class Message {
@JsonView(View.Summary.class)
private Long id;
@JsonView(View.Summary.class)
private LocalDate created;
@JsonView(View.Summary.class)
private String title;
@JsonView(View.Summary.class)
private User author;
private List<User> recipients;
private String body;
}
General Web Improvments
● In the controller
@Autowired
private MessageService messageService;
@JsonView(View.Summary.class)
@RequestMapping("/")
public List<Message> getAllMessages() {
return messageService.getAll();
}
● Output:
[ {
● "id" : 1,
● "created" : "2014-11-14",
● "title" : "Info",
● "author" : {
● "id" : 1,
● "firstname" : "Brian",
●
"lastname" : "Clozel"
● }
● }, {
● "id" : 2,
●
"created" : "2014-11-14",
● "title" : "Warning",
● "author" : {
● "id" : 2,
●
"firstname" : "Stéphane",
● "lastname" : "Nicoll"
● }
● }
General Web Improvments
– @ControllerAdvice improvements
● Can be configured to support defined subset of controllers through
annotations, basePackageClasses, basePackages.
– Example:
● @Controller
● @RequestMapping("/api/article")
● class ArticleApiController {
●
● @RequestMapping(value = "{articleId}", produces = "application/json")
● @ResponseStatus(value = HttpStatus.OK)
● @ResponseBody
● Article getArticle(@PathVariable Long articleId) {
● throw new IllegalArgumentException("[API] Getting article problem.");
● }
● }
General Web Improvments
●
Exception handler handling the api request can be restricted as follows:
●
@ControllerAdvice(annotations = RestController.class)
● class ApiExceptionHandlerAdvice {
●
●
/**
● * Handle exceptions thrown by handlers.
●
*/
● @ExceptionHandler(value = Exception.class)
● @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
●
@ResponseBody
● public ApiError exception(Exception exception, WebRequest request) {
● return new ApiError(Throwables.getRootCause(exception).getMessage());
●
}
● }
Java 8.0 support
l
Hands on!!!!
Testing Improvements
– Active @Bean on the bases of profile can be resolved
programmatically by ActiveProfilesResolver and
registering it via resolver attribute of @ActiveProfiles.
Example:
Scenario : If we want to do testing across the environments (dev,
stagging etc.) for integration testing.
Step 1 : Set the active profile
<container>
<containerId>tomcat7x</containerId>
<systemProperties>
<spring.profiles.active>development</spring.profiles.active>
</systemProperties>
</container>
Testing improvements
public class SpringActiveProfileResolver implements ActiveProfilesResolver {
@Override
public String[] resolve(final Class<?> aClass) {
final String activeProfile System.getProperty("spring.profiles.active");
return new String[] { activeProfile == null ? "integration" : activeProfile };
}
– And in the test class we use the annotation.
@ActiveProfiles(resolver = SpringActiveProfileResolver.class)
public class IT1DataSetup {
......
}
Testing improvements
● SocketUtils class introduced in the spring-core module
allow to start an in memory SMTP server, FTP server,
servlet container etc to enable integration testing that
require use of sockets.
– Example:
@Test public void testErrorFlow() throws Exception {
final int port=SocketUtils.findAvailableServerSocket();
AbstractServerConnectionFactory scf=new
TcpNetServerConnectionFactory(port);
scf.setSingleUse(true);
TcpInboundGateway gateway=new TcpInboundGateway();
gateway.setConnectionFactory(scf);
Java 8.0 support
l
Hands on!!!!

More Related Content

What's hot

Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, mavenFahad Golra
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring SessionDavid Gómez García
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOPHitesh-Java
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depthVinay Kumar
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutesglassfish
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: ServletsFahad Golra
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJiayun Zhou
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web SocketsFahad Golra
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)Fahad Golra
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkRajind Ruparathna
 
Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 javatwo2011
 
Database connect
Database connectDatabase connect
Database connectYoga Raja
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring Sunil kumar Mohanty
 
Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdatePhil Steitz
 

What's hot (18)

Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutes
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: Servlets
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Connection Pooling
Connection PoolingConnection Pooling
Connection Pooling
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望
 
Database connect
Database connectDatabase connect
Database connect
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring
 
Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 Update
 

Viewers also liked

Quartz: What is it?
Quartz: What is it?Quartz: What is it?
Quartz: What is it?alesialucy14
 
Getting Started with Spring Boot
Getting Started with Spring BootGetting Started with Spring Boot
Getting Started with Spring BootDavid Kiss
 
The Spring Framework: A brief introduction to Inversion of Control
The Spring Framework:A brief introduction toInversion of ControlThe Spring Framework:A brief introduction toInversion of Control
The Spring Framework: A brief introduction to Inversion of ControlVisualBee.com
 
Introduction To Angular.js - SpringPeople
Introduction To Angular.js - SpringPeopleIntroduction To Angular.js - SpringPeople
Introduction To Angular.js - SpringPeopleSpringPeople
 
SpringPeople Introduction to Spring Framework
SpringPeople Introduction to Spring FrameworkSpringPeople Introduction to Spring Framework
SpringPeople Introduction to Spring FrameworkSpringPeople
 
Getting Started with Spring Framework
Getting Started with Spring FrameworkGetting Started with Spring Framework
Getting Started with Spring FrameworkEdureka!
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architectureGabriele Falace
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkDineesha Suraweera
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Tobias Trelle
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBMongoDB
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 

Viewers also liked (20)

Spring 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
 
Spring framework core
Spring framework coreSpring framework core
Spring framework core
 
Quartz: What is it?
Quartz: What is it?Quartz: What is it?
Quartz: What is it?
 
Spring 3 to 4
Spring 3 to 4Spring 3 to 4
Spring 3 to 4
 
Getting Started with Spring Boot
Getting Started with Spring BootGetting Started with Spring Boot
Getting Started with Spring Boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Mvc
Spring MvcSpring Mvc
Spring Mvc
 
The Spring Framework: A brief introduction to Inversion of Control
The Spring Framework:A brief introduction toInversion of ControlThe Spring Framework:A brief introduction toInversion of Control
The Spring Framework: A brief introduction to Inversion of Control
 
Introduction To Angular.js - SpringPeople
Introduction To Angular.js - SpringPeopleIntroduction To Angular.js - SpringPeople
Introduction To Angular.js - SpringPeople
 
SpringPeople Introduction to Spring Framework
SpringPeople Introduction to Spring FrameworkSpringPeople Introduction to Spring Framework
SpringPeople Introduction to Spring Framework
 
Getting Started with Spring Framework
Getting Started with Spring FrameworkGetting Started with Spring Framework
Getting Started with Spring Framework
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architecture
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Spring Data, Jongo & Co.
Spring Data, Jongo & Co.
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring boot
Spring bootSpring boot
Spring boot
 
Presentation Spring
Presentation SpringPresentation Spring
Presentation Spring
 

Similar to Spring 4 Features Guide

Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introductionOndrej Mihályi
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfAppster1
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfAppster1
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Gunith Devasurendra
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Dynamic Groovy Edges
Dynamic Groovy EdgesDynamic Groovy Edges
Dynamic Groovy EdgesJimmy Ray
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleSkills Matter
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0Matt Raible
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaPawanMM
 

Similar to Spring 4 Features Guide (20)

Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Dynamic Groovy Edges
Dynamic Groovy EdgesDynamic Groovy Edges
Dynamic Groovy Edges
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
Svcc Groovy Testing
Svcc Groovy TestingSvcc Groovy Testing
Svcc Groovy Testing
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 

Recently uploaded

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

Spring 4 Features Guide

  • 1. By : Sumit Gole & Sourabh Aggarwal Date : 13 August 2015 SPRING 4
  • 4. Spring 3.0 (past stop) ● Application configuration using Java. ● Servlet 3.0 API support ● Support for Java SE 7 ● @MVC additions ● Declarative model validation ● Embedded database support ● Many more....
  • 5. Spring 4.0 (Current Stop) ● Fully support for Java8 features. ● Java 6 <= (Spring) = Java 8 ● Removed depricated packages and methods. ● Groovy Bean Definition DSL. ● Core Container Improvements. ● General Web Improvements. ● WebSocket, SockJS, and STOMP Messaging. ● Testing Improvements.
  • 6. Java 8.0 Support ● Use of lambda expressions. ● In Java 8 a lambda expression can be used anywhere a functional interface is passed into a method. Example: ● public interface RowMapper<T> ● { ● T mapRow(ResultSet rs, int rowNum) throws SQLException; ● }
  • 7. Java 8.0 Support ● For example the Spring JdbcTemplate class contains a method. public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException ● Implementation: jdbcTemplate.query("SELECT * from queries.products", (rs, rowNum) -> { Integer id = rs.getInt("id"); String description = rs.getString("description");});
  • 8. Java 8.0 Support ● Time and Date API ● Spring 4 updated the date conversion framework (data to java object <--> Java object to data) to support JDK 8.0 Time and Date APIs. ● @RequestMapping("/date/{localDate}") ● public String get(@DateTimeFormat(iso = ISO.DATE) LocalDate localDate) ● { ● return localDate.toString(); ● } ● Spring 4 support Java 8 but that does not imply the third party frameworks like Hibernate or Jakson would also support. So be carefull.....
  • 9. Java 8.0 Support ● Repeating Annotations ● Spring 4 respected the repeating annotatiuon convention intrduced by Java 8. ● Example: @PropertySource("classpath:/example1.properties") @PropertySource("classpath:/example2.properties") public class Application {
  • 10. Java 8.0 Support ● Checking for null references in methods is always big pain.... ● Example: public interface EmployeeRepository extends CrudRepository<Employee, Long> { /** * returns the employee for the specified id or * null if the value is not found */ public Employee findEmployeeById(String id); } Calling this method as: Employee employee = employeeRepository.findEmployeeById(“123”); employee.getName(); // get a null pointer exception
  • 11. Java 8.0 Support ● Magic of java.util.Optional ● public interface EmployeeRepository extends CrudRepository<Employee, Long> { ● /** ● * returns the employee for the specified id or ● * null if the value is not found ● */ ● public Optional<Employee> findEmployeeById(String id); ● }
  • 12. Java 8.0 Support ● Java.util.Optional force the programmer to put null check before extracting the information. ● How? Optional<Employee> optional = employeeRepository.findEmployeeById(“123”); if(optional.isPresent()) { Employee employee = optional.get(); employee.getName(); }
  • 13. Java 8.0 Support ● Spring 4.0 use java.util.Optional in following ways: ● Option 1: ● Old way : @Autowired(required=false) OtherService otherService; ● New way: @Autowired ● Optional<OtherService> otherService; ● Option 2: @RequestMapping(“/accounts/ {accountId}”,requestMethod=RequestMethod.POST) void update(Optional<String> accountId, @RequestBody Account account)
  • 14. Java 8.0 Support ● Auto mapping of Parameter name ● Java 8 support preserve method arguments name in compiled code so spring4 can extract the argument name from compiled code. ● What I mean? @RequestMapping("/accounts/{id}") public Account getAccount(@PathVariable("id") String id) ● can be written as @RequestMapping("/accounts/{id}") public Account getAccount(@PathVariable String id)
  • 16. l Groovy Bean Definition DSL ● @Configuration is empowered with Groovy Bean Builder. ● Spring 4.0 provides Groovy DSL to configur Spring applications. ● How it works? <bean id="testBean" class="com.xebia.TestBeanImpl"> <property name="someProperty" value="42"/> <property name="anotherProperty" value="blue"/> </bean> import my.company.MyBeanImpl beans = { myBean(MyBeanImpl) { someProperty = 42 otherProperty = "blue" } }
  • 17. l Groovy Bean Definition DSL ● Additionally it allows to configure Spring bean defination properties. ● How? ● sessionFactory(ConfigurableLocalSessionFactoryBean) { bean -> ● // Sets the initialization method to 'init'. [init-method] ● bean.initMethod = 'init' ● // Sets the destruction method to 'destroy'. [destroy-method] ● bean.destroyMethod = 'destroy' ● Spring + Groovy ---> More Strong and clean implementation.
  • 18. l Groovy Bean Definition DSL ● How both work together? beans { // org.springframework.beans.factory.groovy.GroovyBe anDefinitionReader if (environment.activeProfiles.contains("prof1")) { foo String, 'hello' } else { foo String, 'world' } } ● In above code DSL uses GroovyBeanDefinitionReader to interpret Groovy code.
  • 19. Groovy Bean Definition DSL ● If the bean defined in the previous code is placed in the file config/contextWithProfiles.groovy the following code can be used to get the value for String foo. Example: ApplicationContext context = new GenericGroovyApplicationContext("file:config/contextWithPro files.groovy"); String foo = context.getBean("foo",String.class);
  • 20. Groovy Bean Definition DSL Hands on!!!!
  • 21. l Core Container Improvements. ● Meta Annotations support ● Defining custom annotations that combines many spring annotations. ● Example import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional @Repository @Scope("prototype") @Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 30, isolation=Isolation.SERIALIZABLE) public class OrderDaoImpl implements OrderDao { .....} ● Without writing any logic we have to repeat the above code in many classes!!!!!
  • 22. l Core Container Improvements. ● Spring 4 custom annotation ● import org.springframework.context.annotation.Scope; ● import org.springframework.stereotype.Repository; ● import org.springframework.transaction.annotation.Isolation; ● import org.springframework.transaction.annotation.Propagation; ● import org.springframework.transaction.annotation.Transactional; ● ● @Repository ● @Scope("prototype") ● @Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 30, isolation=Isolation.SERIALIZABLE) ● public @interface MyDao { ● }
  • 23. l Core Container Improvements. ● Spring 4 custom annotation How to use the custom annotation? @MyDao public class OrderDaoImpl implements OrderDao { ... }
  • 24. l Core Container Improvements Generic qualifiers Java genric types can be used as implicit form of qualification. How? public class Dao<T> { ... } @Configuration public class MyConfiguration { @Bean public Dao<Person> createPersonDao() { return new Dao<Person>(); } @Bean public Dao<Organization> createOrganizationDao() { return new Dao<Organization>(); } }
  • 25. Core Container Improvements ● How to call? @Autowired private Dao<Person> dao; ● Spring 4 container identify which bean to inject on the bases of Java generics.
  • 26. Core Container Improvements ● Conditionally bean defination ● Conditionally enable and disable bean defination or whole configuration. ● Spring 3.x @Configuration @Configuration @Profile("Linux") @Profile(“Window”) public class LinuxConfiguration { public class indowConfiguration{ @Bean @Bean public EmailService emailerService() { public EmailService emailerService(){ return new LinuxEmailService(); return new WindowEmailService(); } } } }
  • 27. Core Container Improvements @Conditional is a flexible annotation, is consulted by the container before @Bean is registered. How? The Conditional interface method @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) is overridden. context : provides access to the environment, class loader and container. metadata: metadata of the class being checked.
  • 28. Core Container Improvements ● The previous example would be implemented as public class LinuxCondition implements Condition{ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().getProperty("os.name").contains("Linux"); } } public class WindowsCondition implements Condition{ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().getProperty("os.name").contains("Windows"); } }
  • 29. Core Container Improvements @Configuration public class MyConfiguration { @Bean(name="emailerService") @Conditional(WindowsCondition.class) public EmailService windowsEmailerService(){ return new WindowsEmailService(); } @Bean(name="emailerService") @Conditional(LinuxCondition.class) public EmailService linuxEmailerService(){ return new LinuxEmailService(); } }
  • 30. Core Container Improvements ● @Order and Autowiring – Beans can be orderly wired by adding the @Order annotation in the @Bean implementations as follows @Component @Order(value=1) public class Employee implements Person { .. } @Component @Order(value=2) public class Customer implements Person { ...... } Using the @Autowired List<Person> people; Results in [com.intertech.Employee@a52728a, com.intertech.Customer@2addc751]
  • 32. General Web Improvments – New @RestController annotation with Spring MVC application provide specific implementation for RestFull web services, removing requirement to add @ResponseBody to each of your @RequestMapping. – Spring 3.x @Controller public class SpringContentController { @Autowired UserDetails userDetails; @RequestMapping(value="/springcontent", method=RequestMethod.GET,produces={"application/xml", "application/json"}) @ResponseStatus(HttpStatus.OK) public @ResponseBody UserDetails getUser() { UserDetails userDetails = new UserDetails(); userDetails.setUserName("Krishna"); userDetails.setEmailId("krishna@gmail.com"); return userDetails; }
  • 33. General Web Improvments With @RestController annotation – @RestController public class SpringContentController { @Autowired UserDetails userDetails; @RequestMapping(value="/springcontent", method=RequestMethod.GET,produces={"application/xml", "application/json"}) @ResponseStatus(HttpStatus.OK) public UserDetails getUser() { UserDetails userDetails = new UserDetails(); userDetails.setUserName("Krishna"); userDetails.setEmailId("krishna@gmail.com"); return userDetails; }
  • 34. General Web Improvments – Jakson integration improvements. – Filter the serialized object in the Http Response body with Jakson Serialization view. – @JsonView annotation is used to filter the fields depending on the requirement. e.g. When getting the Collection in Http response then pass only the summary and if single object is requested then return the full object. – Example public class View { interface Summary {} } public class User { @JsonView(View.Summary.class) private Long id; @JsonView(View.Summary.class) private String firstname; @JsonView(View.Summary.class) private String lastname; private String email; private String address; }
  • 35. General Web Improvments public class Message { @JsonView(View.Summary.class) private Long id; @JsonView(View.Summary.class) private LocalDate created; @JsonView(View.Summary.class) private String title; @JsonView(View.Summary.class) private User author; private List<User> recipients; private String body; }
  • 36. General Web Improvments ● In the controller @Autowired private MessageService messageService; @JsonView(View.Summary.class) @RequestMapping("/") public List<Message> getAllMessages() { return messageService.getAll(); } ● Output: [ { ● "id" : 1, ● "created" : "2014-11-14", ● "title" : "Info", ● "author" : { ● "id" : 1, ● "firstname" : "Brian", ● "lastname" : "Clozel" ● } ● }, { ● "id" : 2, ● "created" : "2014-11-14", ● "title" : "Warning", ● "author" : { ● "id" : 2, ● "firstname" : "Stéphane", ● "lastname" : "Nicoll" ● } ● }
  • 37. General Web Improvments – @ControllerAdvice improvements ● Can be configured to support defined subset of controllers through annotations, basePackageClasses, basePackages. – Example: ● @Controller ● @RequestMapping("/api/article") ● class ArticleApiController { ● ● @RequestMapping(value = "{articleId}", produces = "application/json") ● @ResponseStatus(value = HttpStatus.OK) ● @ResponseBody ● Article getArticle(@PathVariable Long articleId) { ● throw new IllegalArgumentException("[API] Getting article problem."); ● } ● }
  • 38. General Web Improvments ● Exception handler handling the api request can be restricted as follows: ● @ControllerAdvice(annotations = RestController.class) ● class ApiExceptionHandlerAdvice { ● ● /** ● * Handle exceptions thrown by handlers. ● */ ● @ExceptionHandler(value = Exception.class) ● @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) ● @ResponseBody ● public ApiError exception(Exception exception, WebRequest request) { ● return new ApiError(Throwables.getRootCause(exception).getMessage()); ● } ● }
  • 40. Testing Improvements – Active @Bean on the bases of profile can be resolved programmatically by ActiveProfilesResolver and registering it via resolver attribute of @ActiveProfiles. Example: Scenario : If we want to do testing across the environments (dev, stagging etc.) for integration testing. Step 1 : Set the active profile <container> <containerId>tomcat7x</containerId> <systemProperties> <spring.profiles.active>development</spring.profiles.active> </systemProperties> </container>
  • 41. Testing improvements public class SpringActiveProfileResolver implements ActiveProfilesResolver { @Override public String[] resolve(final Class<?> aClass) { final String activeProfile System.getProperty("spring.profiles.active"); return new String[] { activeProfile == null ? "integration" : activeProfile }; } – And in the test class we use the annotation. @ActiveProfiles(resolver = SpringActiveProfileResolver.class) public class IT1DataSetup { ...... }
  • 42. Testing improvements ● SocketUtils class introduced in the spring-core module allow to start an in memory SMTP server, FTP server, servlet container etc to enable integration testing that require use of sockets. – Example: @Test public void testErrorFlow() throws Exception { final int port=SocketUtils.findAvailableServerSocket(); AbstractServerConnectionFactory scf=new TcpNetServerConnectionFactory(port); scf.setSingleUse(true); TcpInboundGateway gateway=new TcpInboundGateway(); gateway.setConnectionFactory(scf);