SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
Spring 3
An overview of changes from version 2.5

             Ted Pennings


           8 December 2010
Overview of Changes

 Annotations

 Fewer interfaces

 MVC overhaul

 Dropped binary compatibility with Java 1.4

   Java 5 generics, for(), autoboxing, etc
Spring 3 = Annotations
 Spring 3 emphasizes annotation config

   @Component, @Configuration, etc

   JSR 250 Common Annotations

   JSR 299/330 Bean Injection

   JSR 303 Bean Validation

   Java Persistence API (JPA)
Enabling Annotation
   Configuration
<context:component-scan base-package=”com.foo.bar”>

<mvc:annotation-driven>



also, <aspectj:auto-proxy /> for @Aspects
Annotation Config
              Example
<?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:mvc="http://www.springframework.org/schema/mvc"
	   xsi:schemaLocation="
	   	    http://www.springframework.org/schema/beans	   http://www.springframework.org/schema/
beans/spring-beans-3.0.xsd
	   	    http://www.springframework.org/schema/mvc	 http://www.springframework.org/schema/mvc/
spring-mvc-3.0.xsd
	   	    http://www.springframework.org/schema/context http://www.springframework.org/schema/
context/spring-context-3.0.xsd">

	   <!--
	   	    Scans within the base package of the application for @Components to
	   	    configure as beans
	   -->
	   <context:component-scan base-package="com.tedpennings.bu.cs667" />
	   <mvc:annotation-driven />

</beans>
Annotation
         Taxonomy
@Component and its specializations

    @Service, @Repository

    @Controller

@Configuration + @Bean

@Autowired
@Value
@Component
            Example
   @Component("rssView")
public class RomeRssView extends AbstractView {

    @Override
    protected void renderMergedOutputModel(Map model,
HttpServletRequest request, HttpServletResponse
response) throws Exception {
	
      	 doStuff();

    }

}
@Service Example
   @Service
public class TwitterStatusProvider implements StatusProvider {

    @Autowired
    private CacheRepository cache;

    @Override
    public String getStatus(boolean skipCache) {
        String status = cache.findString(CACHE_KEY);
        if (skipCache || status == null) {
	           status = getStatusFromTwitter();
            cache.cacheString(CACHE_KEY, status, DEFAULT_CACHE_EXPIRY);
        }
        return status;
    }

}
@Configuration
      Classes
Java classes that do the work of XML
Application Context files

Allow much more control over object creation

Instantiated before XML beans

  @Configuration @Beans can be referenced by
  XML beans/config

  Can also reference XML beans
@Config Example
   @Configuration
public class MongoConfiguration {

    @Value("${db.host}")
    private String dbHost;

    @Value("${db.port}")
    private int dbPort;

    @Bean
    @Lazy
    public Mongo mongo() throws UnknownHostException {
        return new Mongo(dbHost, dbPort);
    }

}
MVC Changes
Controller interfaced dropped

@RequestMapping instead of XML config

@Controller instead of explicit XML config

Lots of return types possible



Simplicity
The Simplicity of
    Controllers
@Controller makes a class a controller “bean”
  Specialization of @Component


@RequestMapping defines the URL paths handled by a
class and/or method.
  It is possible to nest paths, as in example on next slide.
  Many different RequestMethods allowed in a @Controller
  {} in @RM path define @PathVariable/@ReqParam


Value of Inheritance
  Annotation caveat
@Controller Example
  @Controller
@RequestMapping({ "/yacht", "/yachts", "/mah-boats" })
public class YachtController {
  @Autowired
  private YachtService service;

    private static final String YACHT_PAGE_VIEW = "yachts/view";

 @RequestMapping(value = "/{yachtKey}", method = GET)
 public String displayYacht(@PathVariable(“yachtKey”) String yachtKey,
Model model) {
    LOG.debug("Displaying Yacht " + yachtKey);
    Yacht yacht = service.findYachtByKey(yachtKey);
    model.addAttribute("yacht", yacht);
   return YACHT_PAGE_VIEW;
 }

}
MVC Annotations

@Controller – an MVC Controller

@RequestMapping

@ModelAttribute

@RequestParam and @PathVariable

@SessionAttributes
Demo
Annotation Config

Working forms

Bean validation (JSR-303)
Controller Method
      Return Types
@Controller methods can return many different types. Often:
  Model
   ModelAndView (use Model.setView(View) or
   Model.setViewName(String))
      Distinction between View and View Name
   String for the view name to display


Can return void if you’ve drank plenty of convention over configuration
koolaid.
   Dangerous if you refactor a lot (or the next person does).


Methods can also be annotated with @RequestBody
   Used to return a value without going through MVC apparatus
      Generally bad form, but good for testing or mock apps.
   @ModelAttribute has the same two distinct meanings as @ModelAttribute
Bean Validation
             (JSR-303)
Constraints are defined by          @Entity
                                   public class Yacht {
annotations on the actual data         @Id
                                       @GeneratedValue(strategy = GenerationType.AUTO)
entities                               private Long id;


Validation is executed                @Size(min = 4, max = 35, message = "Key must be
                                   between {min} and {max} characters long.")
automagically by framework            @NotEmpty(message = "Key is required.")
                                      @Pattern(regexp = "[A-Za-z0-9_-]*", message = "Only
                                   letters, numbers, underscores and hyphens may be used.")
User-friendly errors appear           private String key;

automagically on the view.
                                     @Size(min = 4, max = 35, message = "Name must be
                                   between {min} and {max} characters long.")
Object graphs can be traversed       @NotEmpty(message = "Name is required.")
                                     private String name;
and nested objects are validated
                                       @ValidDate
(or not, if you wish).                 private Date acquisitionDate;

                                   }
Setting Up And Using
     Bean Validation
As simple as @Valid
   Can be applied inside domain to validate child/2nd degree
   objects


BindingResult for errors
   MUST be argument after @Valid argument (quirk)
   RuntimeException if not
   toString() is your friend.


Validating a large object graph is risky.
   Complicates future changes
   On the other hand, very hard to merge BindingResults
Updated Controller
@Controller
public class YachtController {

@RequestMapping(method = POST)
public ModelAndView saveYacht(@Valid Yacht yacht, BindingResult
result, ModelAndView mv) {
    LOG.debug("Attempting to save Yacht: " + yacht.getKey());

    if (result.hasErrors()) {
        LOG.debug("Submission has errors " + result);
        mv.setViewName(MODIFY_YACHT_VIEW);
        return mv;
    }
    service.store(yacht);
    FlashMap.setSuccessMessage("Successfully saved Yacht");
    return createRedirect(yacht);
}

}
Handling Validation
       Errors
Ensure that you have a BindingResult.hasErrors() check in @Controller
   When returning edit view, ensure all needed model attributes are present
   This includes the object being validated if you construct a new Model/
   MV


You may need a call to the root-level form:errors in order to capture object-
level errors (not field-level).
   <form:errors path=“” />


Be sure you interrupt flow so you don’t persist invalid objects
   VALIDATION ERRORS ARE NOT EXCEPTIONS


There is a Hibernate option to validate pre-persist, but this is nuanced
   Legacy objects
   May be incompatible with Spring-managed dependencies
Writing Your Own
      Constraints
Constraints can be combined and composed
  For example, @NotEmpty actually means @NotNull, @Size(min=1) &
  @ReportAsSingleViolation
Write an annotation class
  @Target(ElementType.FIELD)
  @Retention(RetentionPolicy.RUNTIME)
  @Documented (or not)
  @Constraint(validatedBy = YourCustomValidator.class)
  Be sure to add a default message
     These can be Java properties read from a file (Internationalization/i18n)
Write a validator
  Implement ConstraintValidator<AnnotationType, TargetClass>
  Return boolean for isValid(TargetClass object, …)
  Statefulness (via initialize() method)
  Dependency Injection, Constructors, and Hibernate ORM issue
Writing Unit Tests For Validation
             Magic
    A lot of JSR-303 is wizardry and magic beans.
    Write unit tests so you ensure code execution is
    predictable.
    Easiest to write using Spring’s JUnit Test Runner
      Point to an application context field that contains
         <bean id="validator“
         class="org.springframework.validation.beanvalidation.Loca
         lValidatorFactoryBean" />

      Ensure a JSR-303-compliant validator is on your test
      classpath
         Eg, Hibernate Validator
Example Unit Test
 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration({ "classpath:your-persistence.xml",
     "classpath:your-persistence-test.xml" })
 public class YachtValidationTest {

     @Autowired
     private javax.validation.Validator validator;

     private Yacht emptyYacht;

     @Before
     public void setUpEmptyYacht() {
       emptyYacht = new Yacht();
     }

     @Test
     public void theKeyFieldIsRequired() {

         Set<ConstraintViolation<Yacht>> constraintViolations = validator
             .validate(emptyYacht);

         boolean containsYachtKeyViolation = false;

         for (ConstraintViolation<Yacht> violation : constraintViolations) {
           if ("key".equals(violation.getPropertyPath().toString())
                 && violation.getMessageTemplate().contains("required")) {
               containsYachtKeyViolation = true;
           }
         }

         assertTrue(containsYachtKeyViolation);
     }
 }
Even More
       Annotations

JSR 250 Resource Management

JSR 299/330 Bean Injection

JPA!
JSR 250 Resource
  Management
@Resource (typically fields)

@PostConstruct (method)

  Replaces InitializingBean + afterPropertiesSet()

@PreDestroy (method)

  Replaces DisposableBean + destroy()
Bean Injection JSR
javax.inject package:

    @Inject (equivalent to @Autowired)

    @Qualifier (to resolve ambiguities)

    @Named

    @Scope

    @Singleton
JPA Annotations

@PersistenceContext / @PersistenceUnit

@Entity

@Column, @Id, @Enumerated, @ManyToOne, etc



Mixes well with Spring-tx and @Transactional
Basic JPA Configuration
      in Spring 3.0
 PersistenceAnnotationBeanPostProcessor for
 @PersistenceContext/Unit EntityManagers

 LocalContainerEntityManagerFactoryBean to
 bootstrap JPA and read persistence.xml

 Still need to configure provider, eg, Hibernate

 Need to provide data source, either as a
 constructed bean or JNDI reference
Hibernate as JPA
              Provider
    HibernateJpaVendorAdapter + Properties
	   <bean id="jpaVendorAdapter"
	   	    class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
	   	    <property name="showSql" value="true" />
	   	    <property name="generateDdl" value="true" />
	   	    <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
	   </bean>

	   <bean id="hibernateProperties"
	   	    class="org.springframework.beans.factory.config.PropertiesFactoryBean">
	   	    <property name="locations">
	   	    	    <list>
	   	    	    	    <value>classpath:hibernate.properties</value>
                                                                             hibernate.properties:
	   	    	    </list>
	   	    </property>                                                         hibernate.hbm2ddl.auto=update
	   </bean>                                                                  hibernate.connection.autocommit=true
                                                                                hibernate.show.sql=true
	   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"       hibernate.generate_statistics=true
	   	    destroy-method="close">                                                javax.persistence.validation.mode=ddl
                                                                                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
	   	    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
	   	    <property name="url" value="jdbc:mysql://localhost:3306/yourdb" />
	   	    <property name="username" value="user" />
	   	    <property name="password" value="pass" />
	   </bean>
Resources

http://static.springsource.org/spring/docs/
3.0.x/spring-framework-reference/html/

http://static.springsource.org/spring/docs/
3.0.x/javadoc-api/

Spring In Action, 3rd Edition by Craig Walls
(Manning). Excellent survey.

Weitere ähnliche Inhalte

Was ist angesagt?

Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
Database connect
Database connectDatabase connect
Database connectYoga Raja
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification QuestionsSpringMockExams
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESYoga Raja
 
Types of Dependency Injection in Spring
Types of Dependency Injection in SpringTypes of Dependency Injection in Spring
Types of Dependency Injection in SpringSunil kumar Mohanty
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedBG Java EE Course
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsDaniel Ballinger
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate IntroductionRanjan Kumar
 
White Paper On ConCurrency For PCMS Application Architecture
White Paper On ConCurrency For PCMS Application ArchitectureWhite Paper On ConCurrency For PCMS Application Architecture
White Paper On ConCurrency For PCMS Application ArchitectureShahzad
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 

Was ist angesagt? (19)

Deployment
DeploymentDeployment
Deployment
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
 
Jstl 8
Jstl 8Jstl 8
Jstl 8
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Database connect
Database connectDatabase connect
Database connect
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification Questions
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Types of Dependency Injection in Spring
Types of Dependency Injection in SpringTypes of Dependency Injection in Spring
Types of Dependency Injection in Spring
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
 
White Paper On ConCurrency For PCMS Application Architecture
White Paper On ConCurrency For PCMS Application ArchitectureWhite Paper On ConCurrency For PCMS Application Architecture
White Paper On ConCurrency For PCMS Application Architecture
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5
 

Andere mochten auch

Introduction to REST and JAX-RS
Introduction to REST and JAX-RSIntroduction to REST and JAX-RS
Introduction to REST and JAX-RSTed Pennings
 
How to influence shoppers
How to influence shoppersHow to influence shoppers
How to influence shoppersTC Miles
 
Market News Jan 2011
Market News Jan 2011Market News Jan 2011
Market News Jan 2011mhakerem
 
Clive Woodger: Creating Added Value. Post Crisis Trends
Clive Woodger: Creating Added Value. Post Crisis TrendsClive Woodger: Creating Added Value. Post Crisis Trends
Clive Woodger: Creating Added Value. Post Crisis Trendsb2bcg
 
Spring MVC Intro / Gore - Nov NHJUG
Spring MVC Intro / Gore - Nov NHJUGSpring MVC Intro / Gore - Nov NHJUG
Spring MVC Intro / Gore - Nov NHJUGTed Pennings
 
JEE Course - JEE Overview
JEE Course - JEE  OverviewJEE Course - JEE  Overview
JEE Course - JEE Overviewodedns
 
What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)Pavel Bucek
 
JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?Edward Burns
 
CON5898 What Servlet 4.0 Means To You
CON5898 What Servlet 4.0 Means To YouCON5898 What Servlet 4.0 Means To You
CON5898 What Servlet 4.0 Means To YouEdward Burns
 
Designing JEE Application Structure
Designing JEE Application StructureDesigning JEE Application Structure
Designing JEE Application Structureodedns
 

Andere mochten auch (14)

Introduction to REST and JAX-RS
Introduction to REST and JAX-RSIntroduction to REST and JAX-RS
Introduction to REST and JAX-RS
 
How to influence shoppers
How to influence shoppersHow to influence shoppers
How to influence shoppers
 
Market News Jan 2011
Market News Jan 2011Market News Jan 2011
Market News Jan 2011
 
Clive Woodger: Creating Added Value. Post Crisis Trends
Clive Woodger: Creating Added Value. Post Crisis TrendsClive Woodger: Creating Added Value. Post Crisis Trends
Clive Woodger: Creating Added Value. Post Crisis Trends
 
Enterprise Europe Network Presentation - BS 10.12.10
Enterprise Europe Network Presentation - BS 10.12.10Enterprise Europe Network Presentation - BS 10.12.10
Enterprise Europe Network Presentation - BS 10.12.10
 
Spring MVC Intro / Gore - Nov NHJUG
Spring MVC Intro / Gore - Nov NHJUGSpring MVC Intro / Gore - Nov NHJUG
Spring MVC Intro / Gore - Nov NHJUG
 
Framework spring
Framework springFramework spring
Framework spring
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
JEE Course - JEE Overview
JEE Course - JEE  OverviewJEE Course - JEE  Overview
JEE Course - JEE Overview
 
What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)
 
JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
CON5898 What Servlet 4.0 Means To You
CON5898 What Servlet 4.0 Means To YouCON5898 What Servlet 4.0 Means To You
CON5898 What Servlet 4.0 Means To You
 
Designing JEE Application Structure
Designing JEE Application StructureDesigning JEE Application Structure
Designing JEE Application Structure
 

Ähnlich wie Spring 3: What's New

Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Michael Plöd
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc trainingicubesystem
 
Red Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop LabsRed Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop LabsJudy Breedlove
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web FrameworkLuther Baker
 
DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)Hendrik Ebbers
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJini Lee
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice PresentationDmitry Buzdin
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample applicationAntoine Rey
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8Ben Abdallah Helmi
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSam Brannen
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)Markus Eisele
 

Ähnlich wie Spring 3: What's New (20)

Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Red Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop LabsRed Hat Agile integration Workshop Labs
Red Hat Agile integration Workshop Labs
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web Framework
 
DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparison
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
 

Kürzlich hochgeladen

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 

Kürzlich hochgeladen (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Spring 3: What's New

  • 1. Spring 3 An overview of changes from version 2.5 Ted Pennings 8 December 2010
  • 2. Overview of Changes Annotations Fewer interfaces MVC overhaul Dropped binary compatibility with Java 1.4 Java 5 generics, for(), autoboxing, etc
  • 3. Spring 3 = Annotations Spring 3 emphasizes annotation config @Component, @Configuration, etc JSR 250 Common Annotations JSR 299/330 Bean Injection JSR 303 Bean Validation Java Persistence API (JPA)
  • 4. Enabling Annotation Configuration <context:component-scan base-package=”com.foo.bar”> <mvc:annotation-driven> also, <aspectj:auto-proxy /> for @Aspects
  • 5. Annotation Config Example <?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/ beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/ spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/ context/spring-context-3.0.xsd"> <!-- Scans within the base package of the application for @Components to configure as beans --> <context:component-scan base-package="com.tedpennings.bu.cs667" /> <mvc:annotation-driven /> </beans>
  • 6. Annotation Taxonomy @Component and its specializations @Service, @Repository @Controller @Configuration + @Bean @Autowired @Value
  • 7. @Component Example @Component("rssView") public class RomeRssView extends AbstractView { @Override protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { doStuff(); } }
  • 8. @Service Example @Service public class TwitterStatusProvider implements StatusProvider { @Autowired private CacheRepository cache; @Override public String getStatus(boolean skipCache) { String status = cache.findString(CACHE_KEY); if (skipCache || status == null) { status = getStatusFromTwitter(); cache.cacheString(CACHE_KEY, status, DEFAULT_CACHE_EXPIRY); } return status; } }
  • 9. @Configuration Classes Java classes that do the work of XML Application Context files Allow much more control over object creation Instantiated before XML beans @Configuration @Beans can be referenced by XML beans/config Can also reference XML beans
  • 10. @Config Example @Configuration public class MongoConfiguration { @Value("${db.host}") private String dbHost; @Value("${db.port}") private int dbPort; @Bean @Lazy public Mongo mongo() throws UnknownHostException { return new Mongo(dbHost, dbPort); } }
  • 11. MVC Changes Controller interfaced dropped @RequestMapping instead of XML config @Controller instead of explicit XML config Lots of return types possible Simplicity
  • 12. The Simplicity of Controllers @Controller makes a class a controller “bean” Specialization of @Component @RequestMapping defines the URL paths handled by a class and/or method. It is possible to nest paths, as in example on next slide. Many different RequestMethods allowed in a @Controller {} in @RM path define @PathVariable/@ReqParam Value of Inheritance Annotation caveat
  • 13. @Controller Example @Controller @RequestMapping({ "/yacht", "/yachts", "/mah-boats" }) public class YachtController { @Autowired private YachtService service; private static final String YACHT_PAGE_VIEW = "yachts/view"; @RequestMapping(value = "/{yachtKey}", method = GET) public String displayYacht(@PathVariable(“yachtKey”) String yachtKey, Model model) { LOG.debug("Displaying Yacht " + yachtKey); Yacht yacht = service.findYachtByKey(yachtKey); model.addAttribute("yacht", yacht); return YACHT_PAGE_VIEW; } }
  • 14. MVC Annotations @Controller – an MVC Controller @RequestMapping @ModelAttribute @RequestParam and @PathVariable @SessionAttributes
  • 16. Controller Method Return Types @Controller methods can return many different types. Often: Model ModelAndView (use Model.setView(View) or Model.setViewName(String)) Distinction between View and View Name String for the view name to display Can return void if you’ve drank plenty of convention over configuration koolaid. Dangerous if you refactor a lot (or the next person does). Methods can also be annotated with @RequestBody Used to return a value without going through MVC apparatus Generally bad form, but good for testing or mock apps. @ModelAttribute has the same two distinct meanings as @ModelAttribute
  • 17. Bean Validation (JSR-303) Constraints are defined by @Entity public class Yacht { annotations on the actual data @Id @GeneratedValue(strategy = GenerationType.AUTO) entities private Long id; Validation is executed @Size(min = 4, max = 35, message = "Key must be between {min} and {max} characters long.") automagically by framework @NotEmpty(message = "Key is required.") @Pattern(regexp = "[A-Za-z0-9_-]*", message = "Only letters, numbers, underscores and hyphens may be used.") User-friendly errors appear private String key; automagically on the view. @Size(min = 4, max = 35, message = "Name must be between {min} and {max} characters long.") Object graphs can be traversed @NotEmpty(message = "Name is required.") private String name; and nested objects are validated @ValidDate (or not, if you wish). private Date acquisitionDate; }
  • 18. Setting Up And Using Bean Validation As simple as @Valid Can be applied inside domain to validate child/2nd degree objects BindingResult for errors MUST be argument after @Valid argument (quirk) RuntimeException if not toString() is your friend. Validating a large object graph is risky. Complicates future changes On the other hand, very hard to merge BindingResults
  • 19. Updated Controller @Controller public class YachtController { @RequestMapping(method = POST) public ModelAndView saveYacht(@Valid Yacht yacht, BindingResult result, ModelAndView mv) { LOG.debug("Attempting to save Yacht: " + yacht.getKey()); if (result.hasErrors()) { LOG.debug("Submission has errors " + result); mv.setViewName(MODIFY_YACHT_VIEW); return mv; } service.store(yacht); FlashMap.setSuccessMessage("Successfully saved Yacht"); return createRedirect(yacht); } }
  • 20. Handling Validation Errors Ensure that you have a BindingResult.hasErrors() check in @Controller When returning edit view, ensure all needed model attributes are present This includes the object being validated if you construct a new Model/ MV You may need a call to the root-level form:errors in order to capture object- level errors (not field-level). <form:errors path=“” /> Be sure you interrupt flow so you don’t persist invalid objects VALIDATION ERRORS ARE NOT EXCEPTIONS There is a Hibernate option to validate pre-persist, but this is nuanced Legacy objects May be incompatible with Spring-managed dependencies
  • 21. Writing Your Own Constraints Constraints can be combined and composed For example, @NotEmpty actually means @NotNull, @Size(min=1) & @ReportAsSingleViolation Write an annotation class @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented (or not) @Constraint(validatedBy = YourCustomValidator.class) Be sure to add a default message These can be Java properties read from a file (Internationalization/i18n) Write a validator Implement ConstraintValidator<AnnotationType, TargetClass> Return boolean for isValid(TargetClass object, …) Statefulness (via initialize() method) Dependency Injection, Constructors, and Hibernate ORM issue
  • 22. Writing Unit Tests For Validation Magic A lot of JSR-303 is wizardry and magic beans. Write unit tests so you ensure code execution is predictable. Easiest to write using Spring’s JUnit Test Runner Point to an application context field that contains <bean id="validator“ class="org.springframework.validation.beanvalidation.Loca lValidatorFactoryBean" /> Ensure a JSR-303-compliant validator is on your test classpath Eg, Hibernate Validator
  • 23. Example Unit Test @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:your-persistence.xml", "classpath:your-persistence-test.xml" }) public class YachtValidationTest { @Autowired private javax.validation.Validator validator; private Yacht emptyYacht; @Before public void setUpEmptyYacht() { emptyYacht = new Yacht(); } @Test public void theKeyFieldIsRequired() { Set<ConstraintViolation<Yacht>> constraintViolations = validator .validate(emptyYacht); boolean containsYachtKeyViolation = false; for (ConstraintViolation<Yacht> violation : constraintViolations) { if ("key".equals(violation.getPropertyPath().toString()) && violation.getMessageTemplate().contains("required")) { containsYachtKeyViolation = true; } } assertTrue(containsYachtKeyViolation); } }
  • 24. Even More Annotations JSR 250 Resource Management JSR 299/330 Bean Injection JPA!
  • 25. JSR 250 Resource Management @Resource (typically fields) @PostConstruct (method) Replaces InitializingBean + afterPropertiesSet() @PreDestroy (method) Replaces DisposableBean + destroy()
  • 26. Bean Injection JSR javax.inject package: @Inject (equivalent to @Autowired) @Qualifier (to resolve ambiguities) @Named @Scope @Singleton
  • 27. JPA Annotations @PersistenceContext / @PersistenceUnit @Entity @Column, @Id, @Enumerated, @ManyToOne, etc Mixes well with Spring-tx and @Transactional
  • 28. Basic JPA Configuration in Spring 3.0 PersistenceAnnotationBeanPostProcessor for @PersistenceContext/Unit EntityManagers LocalContainerEntityManagerFactoryBean to bootstrap JPA and read persistence.xml Still need to configure provider, eg, Hibernate Need to provide data source, either as a constructed bean or JNDI reference
  • 29. Hibernate as JPA Provider HibernateJpaVendorAdapter + Properties <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true" /> <property name="generateDdl" value="true" /> <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" /> </bean> <bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:hibernate.properties</value> hibernate.properties: </list> </property> hibernate.hbm2ddl.auto=update </bean> hibernate.connection.autocommit=true hibernate.show.sql=true <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" hibernate.generate_statistics=true destroy-method="close"> javax.persistence.validation.mode=ddl hibernate.dialect=org.hibernate.dialect.MySQL5Dialect <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/yourdb" /> <property name="username" value="user" /> <property name="password" value="pass" /> </bean>

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \nThe createRedirect shown is a hack to avoid nasty exposed model attributes. Credit for this code goes to David Ehringer:\n\n private ModelAndView createRedirect(Yacht yacht) {\n String yachtKey = yacht.getKey();\n RedirectView redirect = new RedirectView(&quot;/yacht/&quot; + yachtKey, true);\n // We are doing this rather than simply returning the String version of\n // the view (i.e. redirect:/groups/groupKey) because in the current\n // version of Spring all the model attributes get appended to the URL\n // which is nasty.\n redirect.setExposeModelAttributes(false);\n return new ModelAndView(redirect);\n }\n
  19. \n
  20. \n
  21. Possibilities for ESAPI!\n
  22. You can also use &lt;mvc:annotation-driven /&gt;, but this often registers two conflicting instances of javax.validation.Validator, and causing an ambiguous bean reference exception on the @Autowired injection line in this example. It is easier to explicitly define an instance as above.\n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n