SlideShare a Scribd company logo
1 of 62
Download to read offline
Spring - ADD Developer

                              Annotated Driven Development




Friday, February 13, 2009
About Speaker

   Speaker @ JavaOne, NFJS, Devcon, Borcon
   Sun Certified Java 2 Architect.
   Instructor for VisiBroker for Java, OOAD, Rational Rose,
    and Java Development.
   JBoss Certified Developer




Friday, February 13, 2009
Agenda

                            Annotations and the MV
                            Spring 2.5/3 Annotations
                              – Spring Business Tier
                            Spring Data Tier
                            Spring MVC Tier
                            Summary




Friday, February 13, 2009
Industry Forces

                            Annotations
                              – EJB 3.X
                              – JSR-250 Common Annotations
                              – JSR-299 Web Beans
                            Guice / SEAM
                            XML... way too much XML




Friday, February 13, 2009
Industry Move to Annotations




                                5

Friday, February 13, 2009
Commons Annotation


                            @Resource




      @PreDestroy           @PostConstruct


                               6

Friday, February 13, 2009
EJB Annotation

      Commons
     @Resource
     @PreDestroy
     @PostConstruct




Friday, February 13, 2009
@Home
 EJB Annotation

      Commons                                @SecurityRoles
                                           @Init
     @Resource                                              @EJB
     @PreDestroy
                                                 @MessageDriven
     @PostConstruct
                                     @MethodPermissions
                                                          @Stateful


                                                    @Interceptor
                                      @Inject
                            @RunAs                   @Stateless
                                         @TransactionManagement
                             @TransactionAttribute     7

Friday, February 13, 2009
JPA Annotation

      Commons
     @Resource
     @PreDestroy
     @PostConstruct

      EJB
      @Home                 @RunAs
      @EJB                  @MethodPermissions
      @MessageDriven        @Init
                            @Interceptor
      @Stateful
                            @TransactionManagement
      @Inject
                            @TransactionAttribute
      @Stateless
      @SecurityRoles                                 8

Friday, February 13, 2009
@Column
 JPA Annotation
                             @JoinColumn       @GeneratedValue
      Commons                                  @Entity
     @Resource
     @PreDestroy
                                                    @Table
     @PostConstruct
                                 @Version @Serialized
   EJB
   @Home            @RunAs                      @OneToMany
   @EJB             @MethodPermissions
   @MessageDriven @Init                   @OneToOne @Id
 ManyToMany         @Interceptor
   @Stateful                                 @ManyToOne
                    @TransactionManagement
   @Inject                                  @AssociationTable
                    @TransactionAttribute
   @Stateless
                                 @EmbeddedId
              @DisciminatorColumn
   @SecurityRoles                                8 @Transien

Friday, February 13, 2009
JPA Annotation

                     JPA
      Commons
                                     @Table     @ManyToMany
                     @Entity
     @Resource
                     @GeneratedValue @Column    @DisciminatorCol
     @PreDestroy
                                     @OneToMany
                     @JoinColumn
     @PostConstruct                             @AssociationTable
                                     @OneToOne
                     @Version
                                                @EmbeddedId
                     @Serialized     @Id
      EJB
                                     @ManyToOne @Transient
      @Home          @RunAs
      @EJB             @MethodPermissions
      @MessageDriven @Init
                       @Interceptor
      @Stateful
                       @TransactionManagement
      @Inject
                       @TransactionAttribute
      @Stateless
      @SecurityRoles                               9

Friday, February 13, 2009
Web Services

 @Resource
                                              @ManyToMany
@PreDestroy
                                                @Table
                            @WebServiceRef    @DisciminatorCol
 PostConstruct
                                              @Column
                                              @AssociationTable
                            @WebServiceRefs
@Home                                         @OneToMany
@MethodPermissions
                                              @EmbeddedId
 @EJB
@Init
                                               @OneToOne
                                              @Transient
@MessageDriven
@Interceptor
                                                  @Entity
@TransactionManagement                          @ManyToOne
@Stateful                                         @GeneratedV
@TransactionAttribute
 @Inject                                          @Id
                                                  @JoinColumn
@Stateless                                        @Version
                                                  @Serialized
 SecurityRoles
                                                  @RunAs
                                                  10

Friday, February 13, 2009
Web Beans
                            @New
 @Resource                  @Out
                                             @ManyToMany
@PreDestroy                 @In
                                               @Table
                                             @DisciminatorCol
 PostConstruct              @Model            @WebServiceRef
                                             @Column
@WebServiceRefs                              @AssociationTable
                            @SessionScoped
@Home                                        @OneToMany
@MethodPermissions          @Current         @EmbeddedId
  @EJB
@Init
                            @LoggedIn         @OneToOne
                                             @Transient
@MessageDriven
@Interceptor
                                                 @Entity
                            @Produces
@TransactionManagement                         @ManyToOne
 @Stateful                                       @GeneratedV
@TransactionAttribute       @Interceptor
  @Inject                                        @Id
                                                 @JoinColumn
                            @Secure
 @Stateless                                      @Version
                            @Decorator           @Serialized
 SecurityRoles
                            @Synchronous
                                                 @RunAs
                            @Asynchronous        11

Friday, February 13, 2009
Servlet 3
  @New               @WebServlet
 @Resource                                          @Out
                     @ServletFilter              @ManyToMany
   @In
@PreDestroy
                     @InitParam                   @Table
                                                 @DisciminatorCol
 PostConstruct                                   @WebServiceRef
                                                    @Model
                     @WebServletContextListenter @Column
@WebServiceRefs
   @SessionScoped                                @AssociationTable
@Home                                           @OneToMany
@MethodPermissions
                                                    @Current
                                                 @EmbeddedId
  @EJB
@Init
   @LoggedIn
                                                 @OneToOne
                                                 @Transient
@MessageDriven
@Interceptor
                                                    @Entity
                                                    @Produces
@TransactionManagement                            @ManyToOne
 @Stateful
   @Interceptor                                     @GeneratedV
@TransactionAttribute
  @Inject                                            @Id
                                                    @JoinColumn
                                                    @Secure
 @Stateless
   @Decorator                                       @Version
                                                    @Serialized
 SecurityRoles
                                                    @Synchronou
                                                    @RunAs
   @Asynchronous
                                                    12

Friday, February 13, 2009
JSR 303: Bean Validation
  @New
 @Resource                                            @Out
                                                  @ManyToMany
                            @NotNull
   @In
@PreDestroy
                                                    @Table
                            @ConstraintValidator @DisciminatorCol
 PostConstruct                                    @WebServiceRef
                                                      @Model
                                                  @Column
                            @Length
@WebServiceRefs
   @SessionScoped                                 @AssociationTable
@Home                                            @OneToMany
                            @Min
@MethodPermissions
                                                      @Current
                                                  @EmbeddedId
  @EJB                      @Pattern
@Init
   @LoggedIn
                                                  @OneToOne
                                                  @Transient
@MessageDriven
@Interceptor                @Size                     @Entity
                                                      @Produces
@TransactionManagement                             @ManyToOne
 @Stateful                  @Valid
   @Interceptor                                       @GeneratedV
@TransactionAttribute
  @Inject                                        @ServletFilter
                            @NotEmpty                 @Id
                                                      @JoinColumn
  @WebServlet                                         @Secure
 @Stateless
   @Decorator                                         @Version
                                                      @Serialized
                                                 @WebServletContex
 SecurityRoles
  @InitParam                                          @Synchronou
                                                      @RunAs
   @Asynchronous
                                                     13

Friday, February 13, 2009
JSR 303: Bean Validation
  @New
                                 @NotNull
 @Resource                       @Out
                             @ManyToMany
   @In
@PreDestroy
                               @Table
   @ConstraintValidator      @DisciminatorCol
                                 @Length
 PostConstruct               @WebServiceRef
                                 @Model
                             @Column
@WebServiceRefs
   @SessionScoped            @AssociationTable
@Home                       @OneToMany
@MethodPermissions
   @Min                          @Pattern
                                 @Current
                             @EmbeddedId
  @EJB
@Init
   @LoggedIn
                             @OneToOne
                             @Transient
@MessageDriven
@Interceptor
   @Size                         @Entity
                                 @Valid
                                 @Produces
@TransactionManagement        @ManyToOne
 @Stateful
   @Interceptor                  @GeneratedV
@TransactionAttribute
  @Inject                   @ServletFilter
                                 @Id
   @NotEmpty                     @JoinColumn
  @WebServlet                    @Secure
 @Stateless
   @Decorator                    @Version
                                 @Serialized
                            @WebServletContex
 SecurityRoles
  @InitParam                     @Synchronou
                                 @RunAs
   @Asynchronous
                                14

Friday, February 13, 2009
JSR-299 Context and DI for Java

    @NonBinding                @Realizes
    @Named                     @Initializer
    @Stereotype                @New
    @Interceptor               @Current
    @InterceptorBindingType    @Production
    @Decorator                 @Standard
    @Decorates                 @Obtains
    @ScopeType                 @Initialized
    @ApplicationScoped         @Deployed
    @RequestScoped             @Observes
    @SessionScoped             @IfExists
    @ConverationScoped         @Asynchronously
    @Dependent                 @AfterTransactionCompletion
    @BindingType               @AfterTransactionFailure
    @DeploymentType            @AfterTransactionSuccess
    @Produces                  @BeforeTransactionCompletion
    @Disposes                  @Fires
    @Specializes               @Model
                                                            15

Friday, February 13, 2009
Annotation Frustrations

                            Not Mentioned
                             JMX 2.0
                             JAX-RS
                             JUnit 4 / TestNG
                             AOP frameworks
                             Spring




Friday, February 13, 2009
Spring Annotations




Friday, February 13, 2009
Spring 3 - Annotation Support

   JSR 250 - @PostConstruct, @Resource…
   JAX-WS 2.0’s - @WebServiceRef
   EJB 3.0 - @EJB
   MVC annotations - @RequestParam, @RequestMapping…
   Test Enhancements - Junit 4.4 and TestNG
   Stereotypes - @Component, @Controller…
   Spring enhancements - @Autowired,
   AOP - @Configurable




Friday, February 13, 2009
Spring Annotations

                            Spring 2.x Data Access
                             Annotations
                            Spring 2.x Aspects
                            Spring 2.5 Context Annotations
                            Spring 2.5 Stereotypes
                            Spring 2.5 Factory Annotations
                            Spring 2.5 MVC Annotations
                            Spring 3.0 REST




Friday, February 13, 2009
Spring 2.x Data Access Annotations

   @Transactional
         – Provides annotation driven demarcation for
           transactions
   @Repository
         – Indicates that a class functions as a repository or
           a data access object (DAO)
         – Exceptions are transparently translated
            • Springs DataAccessException Hierarchy




Friday, February 13, 2009
Spring 2.5 Stereotypes

   @Component **
         – Indicates that a class is a component
         – Class is a candidate for auto-detection
         – Custom component extensions
   @Controller
         – Specialized Component
         – Typically used with RequestMapping annotation
         – Discussed in section on web mvc
   @Repository
         – 2.0 stereotype… previously mentioned
         – Now an extension of @Component
   @Service
         – Intended to be a business service facade


Friday, February 13, 2009
Spring 2.5 Factory Annotations

   @Autowired
     – Marks a constructor, field, setter or config method for injection.
     – Fields are injected
         • After construction
         • Before config methods
         – @Autowired(required=false)
         – Config:
          AutowiredAnnotationBeanPostProcessor
                •
   @Configurable
         – Marks class as being eligible for Spring-driven configuration
         – Used with AspectJ
   @Qualifier
     – Qualifies a bean for autowiring
     – May be customized
   @Required
     – Marks a method as being injection required



Friday, February 13, 2009
Types of Injections
      Constructor




      Setter




      Field



                            23

Friday, February 13, 2009
New Injection Type
      configuration
        method




      with any
        number of
        arguments




                            24

Friday, February 13, 2009
Let me Qualify that

   @Autowired
   @Qualifier(“xyzDataSourceName”)
   Private DataSource dataSource

   Or
   @Autowired
   public void init(@Qualifier(“xyzNAme”) DataSource
                 dataSource, Object2 obj)
   {…}




Friday, February 13, 2009
DEMO




Friday, February 13, 2009
Spring / JPA




Friday, February 13, 2009
JPA - Specification

   Packaging
   Entities
   Entity Operations
   Queries
   Metadata
   Life-cycle Model
   Callbacks




Friday, February 13, 2009
Persistence.xml

   In the classpath under the META-INF directory.

   <persistence-unit name=quot;unit1quot; transaction-type=quot;RESOURCE_LOCALquot;>
            <provider>org.hibernate.ejb.HibernatePersistence</provider>
            <properties>
                     <property name=quot;hibernate.hbm2ddl.autoquot; value=quot;createquot;/>
                     <property name=quot;hibernate.ejb.autodetectionquot; value=quot;classquot;/>
                     <property name=quot;hibernate.connection.urlquot;
                             value=quot;jdbc:hsqldb:hsql://localhost:1234/employeequot;/>
                     <property name=quot;hibernate.connection.driver_classquot;
                             value=quot;org.hsqldb.jdbcDriverquot;/>
                     <property name=quot;hibernate.connection.usernamequot; value=quot;saquot;/>
                     <property name=quot;hibernate.connection.passwordquot; value=quot;quot;/>
            </properties>
    </persistence-unit>
   </persistence>




Friday, February 13, 2009
Customer Entity (from spec)


       @Entity(access=FIELD)
       public class Customer {
        @Id(generate=AUTO) Long id;
        @Version protected int version;
        @ManyToOne Address address;
        @Basic String description;
        @OneToMany(targetEntity=com.acme.Order.class,
        mappedBy=quot;customerquot;)
        Collection orders = new Vector();

          @ManyToMany(mappedBy=quot;customersquot;)
          Set<DeliveryService> serviceOptions = new HashSet();
          public Customer() {}

          public Collection getOrders() { return orders; }
          public Set<DeliveryService> getServiceOptions() {



Friday, February 13, 2009
JPA Persistence Interfaces

   EntityManager
         – Interface to interact with persistence context.
         – @PersistenceContext

   EntityManagerFactory
         – Creates an EntityManager
         – @PersistenceUnit




Friday, February 13, 2009
Acquiring a Manager

   Injection in Stateless Bean
     @PersistenceContext
     public EntityManager em;
   OR
     @PersistenceContext(unitName=quot;orderquot;)
     EntityManager em;
   From Java Application
     EntityManagerFactory emf =
           Persistence.createEntityManagerFactory(quot;unit1quot;);
     EntityManager em = emf.createEntityManager();




Friday, February 13, 2009
Spring 2 JPA Support

   org.springframework.orm.jpa package
   Contains subset of the JPA container
   JpaDaoSupport
         – similar to other DAO support classes like
           HibernateDaoSupport
   LocalEntityManagerFactoryBean
         – Provides resource bootstrapping for non-jndi lookups




Friday, February 13, 2009
Spring / JPA Approaches

   JpaDaoSupport Approach
     – Not preferred approach
     – Similar to HibernateDaoSupport
     – Requires Spring Configuration of the
       EntityManager
   Pure JPA Approach
     – Preferred approach
     – No spring references necessary in the code
        • with the exception of @Transactional




                                           34

Friday, February 13, 2009
Approach 2: Spring / Pure JPA Configuration


       Leverage the persistence.xml in classpath:/META-INF
       <bean id=quot;entityManagerFactoryquot;
          class=quot;org.springframework.orm.jpa.LocalEntityManagerFactoryBeanquot; >
         <property name=quot;persistenceUnitNamequot; value=quot;unit1quot;/>
       </bean>

       DAO with no Spring references, however it contains
          @PersistenceContext annotated EntityManager
        <bean id=quot;conferenceDaoquot;
         class=quot;com.codementor.jpa.domain.ConferenceDAOImplquot;/>

       Spring configuration which injects JPA annotationed
          EntityManager
        <bean
         class=quot;org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProces
         sor“ />




Friday, February 13, 2009
Pure JPA Code Example: ConferenceDaoImpl

   package com.nfjs.jpa;


     import java.util.List;
     import javax.persistence.EntityManager;
     import javax.persistence.PersistenceContext;

     import org.springframework.transaction.annotation.Transactional;

     public class ConferenceDAOImpl implements ConferenceDAO {

            @PersistenceContext
            private EntityManager entityManager;



            public void setEntityManager(EntityManager entityManager) {
                this.entityManager = entityManager;
            }
         – ...
                                                              36

Friday, February 13, 2009
Pure JPA Spring Configuration

 <bean id=quot;entityManagerFactoryquot;
   class=quot;org.springframework.orm.jpa.LocalEntityManagerFactoryBeanquot; >
          <property name=quot;persistenceUnitNamequot; value=quot;nfjsquot;/>
       </bean>


 <bean id=quot;conferenceDaoquot; class=quot;com.nfjs.jpa.ConferenceDAOImplquot;/>


   <bean
   class=quot;org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessorquot;
   />



   </beans>




                                                                      37

Friday, February 13, 2009
No PU No Problem

   The LocalContainerEntityManagerFactoryBean can be
     configured with all Persistent Unit information.

    <bean id=quot;entityManagerFactoryquot;
     class=quot;org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBeanquot;>
      <property name=quot;dataSourcequot; ref=quot;dataSourcequot;/>
      <property name=quot;jpaVendorAdapterquot;>
        <bean class=quot;org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapterquot;>
         <property name=quot;showSqlquot; value=quot;truequot;/>
         <property name=quot;generateDdlquot; value=quot;truequot;/>
         <property name=quot;databasePlatformquot;
            value=quot;org.hibernate.dialect.HSQLDialectquot;/>
        </bean>
      </property>
    </bean>




Friday, February 13, 2009
Transactions

   XML Configuration
   <tx:annotation-driven />

   Annotation
   @Transactional(readOnly = false,
     propagation = Propagation.REQUIRES_NEW)
   Public void doSomething() {


   ** transaction manger bean id must be transactionManger or configured
    with the xml configuration above.




Friday, February 13, 2009
Test JPA with Spring

   public class SpeakerDAOTest extends AbstractJpaTests {

   private SpeakerDAO speakerDao;

     public void setSpeakerDao(SpeakerDAO speakerDao) {
       this.speakerDao = speakerDao;
     }

     protected String[] getConfigLocations() {
       return new String[] {quot;classpath:/jpaContext.xmlquot;};
     }

     protected void onSetUpInTransaction() throws Exception {
       jdbcTemplate.execute(
     quot;insert into speaker (id, name, company) values (1, 'Ken', 'CodeMentor')quot;);




Friday, February 13, 2009
AbstractJpaTests Benefits

   getConfigLocations ()
         – Separates test from production configuration
         – Allows for multiple configurations
   Injected Dependencies By Type
     – field references
   Every Test
         – Starts a Transactions
         – Rolls back Transaction
   Leverage jdbcTemplate for SQL checks




Friday, February 13, 2009
DEMO




Friday, February 13, 2009
Spring MVC




Friday, February 13, 2009
Spring 2.5 MVC Annotations

   @Controller
         – Stereotype used to “Controller” of MVC
         – Scanned for RequestMappings
   @RequestMapping
         – Annotates a handler method for a request
         – Very flexible
   @RequestParam
         – Annotates that a method parameter should be bound to a
           web request parameter
   @SessionAttributes
         – Marks session attributes that a handler uses




Friday, February 13, 2009
New Controller Issues

   Doesn’t implement an Interface
   Multiple request mappings
   High degree of flexibility




                                     45

Friday, February 13, 2009
Advantages of Controller Interfaces




                                       46

Friday, February 13, 2009
Advantages of Controller Interfaces



                                         It looks like your
                                       trying to build a
                                         controller




                                              46

Friday, February 13, 2009
Advantages of Controller Interfaces




                                       46

Friday, February 13, 2009
A World Without Rules
                            Return Type?
                            Parameters?




                                            47

Friday, February 13, 2009
@RequestMapping - Extreme Flexibility

   Parameters can be
     – Request / response / session
     – WebRequest
     – InputStream
     – OutputStream
     – @RequestParam
     – +++
   Return types
         –   ModelAndView Object
         –   Model Object
         –   Map for exposing model
         –   View Object
         –   String which is a view name
         –   Void… if method wrote the response content directly



Friday, February 13, 2009
Spring 2.5 Controller Example

   @Controller
   public class ConfController {

       @Autowired
       private confDB confDB;

       @RequestMapping(quot;/sessionListquot;)
       public String showSessionList(ModelMap model) {
         model.addAttribute(quot;sessionsquot;, this.confDB.getSessions());
         return quot;sessionListquot;;
       }

       @RequestMapping(quot;/speakerImagequot;)
       public void streamSpeakerImage(@RequestParam(quot;namequot;) String name,
                                           OutputStream outputStream) throws IOException   {
         this.confDB.getSpeakerImage(name,outputStream);
       }

       @RequestMapping(quot;/clearDatabasequot;)
       public String clearDB() {
         this.confDB.clear();
         return quot;redirect:sessionListquot;;
       }
   }

Friday, February 13, 2009
Spring MVC By Convention

                                              Conventions:
                                              hotel = HotelController
                            GET /hotel/list   list = method
   View selected
   from request
   path


   Added to
   Model




                                                           50

Friday, February 13, 2009
Multi-Action Convention




                            /hotel/index

                            /hotel/show

                            /hotel/list




                                           51

Friday, February 13, 2009
Working With Parameters




                            /hotel/show?id=42




                                                52

Friday, February 13, 2009
@PathVariable - RESTFUL

   GET /owner/show/2




                            53

Friday, February 13, 2009
Submitting Forms




                            54

Friday, February 13, 2009
Demo




Friday, February 13, 2009
Summary - ADD



                            I’m sorry...
                                Were we talking about something...


                              Oh Yeah...
                                  ADD




Friday, February 13, 2009
Summary


                             @nnotations

                              They @re every where!

                              They c@n incre@se productivity




Friday, February 13, 2009
Questions



                             Please Fill Out Surveys




                            kensipe@gmail.com

                            twitter: @kensipe

                            kensipe.blogspot.com

Friday, February 13, 2009

More Related Content

Viewers also liked

Spring MVC Architecture Tutorial
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture TutorialJava Success Point
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerZeroTurnaround
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
SpringFramework Overview
SpringFramework OverviewSpringFramework Overview
SpringFramework Overviewzerovirus23
 
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
 
Spring Mvc,Java, Spring
Spring Mvc,Java, SpringSpring Mvc,Java, Spring
Spring Mvc,Java, Springifnu bima
 
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 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVCGuy Nir
 

Viewers also liked (11)

Spring MVC Architecture Tutorial
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture Tutorial
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen Hoeller
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
SpringFramework Overview
SpringFramework OverviewSpringFramework Overview
SpringFramework Overview
 
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
 
Spring Mvc,Java, Spring
Spring Mvc,Java, SpringSpring Mvc,Java, Spring
Spring Mvc,Java, Spring
 
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 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 

Recently uploaded

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 

Recently uploaded (20)

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 

Spring 3 Annotated Development

  • 1. Spring - ADD Developer Annotated Driven Development Friday, February 13, 2009
  • 2. About Speaker Speaker @ JavaOne, NFJS, Devcon, Borcon Sun Certified Java 2 Architect. Instructor for VisiBroker for Java, OOAD, Rational Rose, and Java Development. JBoss Certified Developer Friday, February 13, 2009
  • 3. Agenda Annotations and the MV Spring 2.5/3 Annotations – Spring Business Tier Spring Data Tier Spring MVC Tier Summary Friday, February 13, 2009
  • 4. Industry Forces Annotations – EJB 3.X – JSR-250 Common Annotations – JSR-299 Web Beans Guice / SEAM XML... way too much XML Friday, February 13, 2009
  • 5. Industry Move to Annotations 5 Friday, February 13, 2009
  • 6. Commons Annotation @Resource @PreDestroy @PostConstruct 6 Friday, February 13, 2009
  • 7. EJB Annotation Commons @Resource @PreDestroy @PostConstruct Friday, February 13, 2009
  • 8. @Home EJB Annotation Commons @SecurityRoles @Init @Resource @EJB @PreDestroy @MessageDriven @PostConstruct @MethodPermissions @Stateful @Interceptor @Inject @RunAs @Stateless @TransactionManagement @TransactionAttribute 7 Friday, February 13, 2009
  • 9. JPA Annotation Commons @Resource @PreDestroy @PostConstruct EJB @Home @RunAs @EJB @MethodPermissions @MessageDriven @Init @Interceptor @Stateful @TransactionManagement @Inject @TransactionAttribute @Stateless @SecurityRoles 8 Friday, February 13, 2009
  • 10. @Column JPA Annotation @JoinColumn @GeneratedValue Commons @Entity @Resource @PreDestroy @Table @PostConstruct @Version @Serialized EJB @Home @RunAs @OneToMany @EJB @MethodPermissions @MessageDriven @Init @OneToOne @Id ManyToMany @Interceptor @Stateful @ManyToOne @TransactionManagement @Inject @AssociationTable @TransactionAttribute @Stateless @EmbeddedId @DisciminatorColumn @SecurityRoles 8 @Transien Friday, February 13, 2009
  • 11. JPA Annotation JPA Commons @Table @ManyToMany @Entity @Resource @GeneratedValue @Column @DisciminatorCol @PreDestroy @OneToMany @JoinColumn @PostConstruct @AssociationTable @OneToOne @Version @EmbeddedId @Serialized @Id EJB @ManyToOne @Transient @Home @RunAs @EJB @MethodPermissions @MessageDriven @Init @Interceptor @Stateful @TransactionManagement @Inject @TransactionAttribute @Stateless @SecurityRoles 9 Friday, February 13, 2009
  • 12. Web Services @Resource @ManyToMany @PreDestroy @Table @WebServiceRef @DisciminatorCol PostConstruct @Column @AssociationTable @WebServiceRefs @Home @OneToMany @MethodPermissions @EmbeddedId @EJB @Init @OneToOne @Transient @MessageDriven @Interceptor @Entity @TransactionManagement @ManyToOne @Stateful @GeneratedV @TransactionAttribute @Inject @Id @JoinColumn @Stateless @Version @Serialized SecurityRoles @RunAs 10 Friday, February 13, 2009
  • 13. Web Beans @New @Resource @Out @ManyToMany @PreDestroy @In @Table @DisciminatorCol PostConstruct @Model @WebServiceRef @Column @WebServiceRefs @AssociationTable @SessionScoped @Home @OneToMany @MethodPermissions @Current @EmbeddedId @EJB @Init @LoggedIn @OneToOne @Transient @MessageDriven @Interceptor @Entity @Produces @TransactionManagement @ManyToOne @Stateful @GeneratedV @TransactionAttribute @Interceptor @Inject @Id @JoinColumn @Secure @Stateless @Version @Decorator @Serialized SecurityRoles @Synchronous @RunAs @Asynchronous 11 Friday, February 13, 2009
  • 14. Servlet 3 @New @WebServlet @Resource @Out @ServletFilter @ManyToMany @In @PreDestroy @InitParam @Table @DisciminatorCol PostConstruct @WebServiceRef @Model @WebServletContextListenter @Column @WebServiceRefs @SessionScoped @AssociationTable @Home @OneToMany @MethodPermissions @Current @EmbeddedId @EJB @Init @LoggedIn @OneToOne @Transient @MessageDriven @Interceptor @Entity @Produces @TransactionManagement @ManyToOne @Stateful @Interceptor @GeneratedV @TransactionAttribute @Inject @Id @JoinColumn @Secure @Stateless @Decorator @Version @Serialized SecurityRoles @Synchronou @RunAs @Asynchronous 12 Friday, February 13, 2009
  • 15. JSR 303: Bean Validation @New @Resource @Out @ManyToMany @NotNull @In @PreDestroy @Table @ConstraintValidator @DisciminatorCol PostConstruct @WebServiceRef @Model @Column @Length @WebServiceRefs @SessionScoped @AssociationTable @Home @OneToMany @Min @MethodPermissions @Current @EmbeddedId @EJB @Pattern @Init @LoggedIn @OneToOne @Transient @MessageDriven @Interceptor @Size @Entity @Produces @TransactionManagement @ManyToOne @Stateful @Valid @Interceptor @GeneratedV @TransactionAttribute @Inject @ServletFilter @NotEmpty @Id @JoinColumn @WebServlet @Secure @Stateless @Decorator @Version @Serialized @WebServletContex SecurityRoles @InitParam @Synchronou @RunAs @Asynchronous 13 Friday, February 13, 2009
  • 16. JSR 303: Bean Validation @New @NotNull @Resource @Out @ManyToMany @In @PreDestroy @Table @ConstraintValidator @DisciminatorCol @Length PostConstruct @WebServiceRef @Model @Column @WebServiceRefs @SessionScoped @AssociationTable @Home @OneToMany @MethodPermissions @Min @Pattern @Current @EmbeddedId @EJB @Init @LoggedIn @OneToOne @Transient @MessageDriven @Interceptor @Size @Entity @Valid @Produces @TransactionManagement @ManyToOne @Stateful @Interceptor @GeneratedV @TransactionAttribute @Inject @ServletFilter @Id @NotEmpty @JoinColumn @WebServlet @Secure @Stateless @Decorator @Version @Serialized @WebServletContex SecurityRoles @InitParam @Synchronou @RunAs @Asynchronous 14 Friday, February 13, 2009
  • 17. JSR-299 Context and DI for Java  @NonBinding  @Realizes  @Named  @Initializer  @Stereotype  @New  @Interceptor  @Current  @InterceptorBindingType  @Production  @Decorator  @Standard  @Decorates  @Obtains  @ScopeType  @Initialized  @ApplicationScoped  @Deployed  @RequestScoped  @Observes  @SessionScoped  @IfExists  @ConverationScoped  @Asynchronously  @Dependent  @AfterTransactionCompletion  @BindingType  @AfterTransactionFailure  @DeploymentType  @AfterTransactionSuccess  @Produces  @BeforeTransactionCompletion  @Disposes  @Fires  @Specializes  @Model 15 Friday, February 13, 2009
  • 18. Annotation Frustrations Not Mentioned JMX 2.0 JAX-RS JUnit 4 / TestNG AOP frameworks Spring Friday, February 13, 2009
  • 20. Spring 3 - Annotation Support JSR 250 - @PostConstruct, @Resource… JAX-WS 2.0’s - @WebServiceRef EJB 3.0 - @EJB MVC annotations - @RequestParam, @RequestMapping… Test Enhancements - Junit 4.4 and TestNG Stereotypes - @Component, @Controller… Spring enhancements - @Autowired, AOP - @Configurable Friday, February 13, 2009
  • 21. Spring Annotations Spring 2.x Data Access Annotations Spring 2.x Aspects Spring 2.5 Context Annotations Spring 2.5 Stereotypes Spring 2.5 Factory Annotations Spring 2.5 MVC Annotations Spring 3.0 REST Friday, February 13, 2009
  • 22. Spring 2.x Data Access Annotations @Transactional – Provides annotation driven demarcation for transactions @Repository – Indicates that a class functions as a repository or a data access object (DAO) – Exceptions are transparently translated • Springs DataAccessException Hierarchy Friday, February 13, 2009
  • 23. Spring 2.5 Stereotypes @Component ** – Indicates that a class is a component – Class is a candidate for auto-detection – Custom component extensions @Controller – Specialized Component – Typically used with RequestMapping annotation – Discussed in section on web mvc @Repository – 2.0 stereotype… previously mentioned – Now an extension of @Component @Service – Intended to be a business service facade Friday, February 13, 2009
  • 24. Spring 2.5 Factory Annotations @Autowired – Marks a constructor, field, setter or config method for injection. – Fields are injected • After construction • Before config methods – @Autowired(required=false) – Config: AutowiredAnnotationBeanPostProcessor • @Configurable – Marks class as being eligible for Spring-driven configuration – Used with AspectJ @Qualifier – Qualifies a bean for autowiring – May be customized @Required – Marks a method as being injection required Friday, February 13, 2009
  • 25. Types of Injections Constructor Setter Field 23 Friday, February 13, 2009
  • 26. New Injection Type configuration method with any number of arguments 24 Friday, February 13, 2009
  • 27. Let me Qualify that @Autowired @Qualifier(“xyzDataSourceName”) Private DataSource dataSource Or @Autowired public void init(@Qualifier(“xyzNAme”) DataSource dataSource, Object2 obj) {…} Friday, February 13, 2009
  • 29. Spring / JPA Friday, February 13, 2009
  • 30. JPA - Specification Packaging Entities Entity Operations Queries Metadata Life-cycle Model Callbacks Friday, February 13, 2009
  • 31. Persistence.xml In the classpath under the META-INF directory. <persistence-unit name=quot;unit1quot; transaction-type=quot;RESOURCE_LOCALquot;> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name=quot;hibernate.hbm2ddl.autoquot; value=quot;createquot;/> <property name=quot;hibernate.ejb.autodetectionquot; value=quot;classquot;/> <property name=quot;hibernate.connection.urlquot; value=quot;jdbc:hsqldb:hsql://localhost:1234/employeequot;/> <property name=quot;hibernate.connection.driver_classquot; value=quot;org.hsqldb.jdbcDriverquot;/> <property name=quot;hibernate.connection.usernamequot; value=quot;saquot;/> <property name=quot;hibernate.connection.passwordquot; value=quot;quot;/> </properties> </persistence-unit> </persistence> Friday, February 13, 2009
  • 32. Customer Entity (from spec) @Entity(access=FIELD) public class Customer { @Id(generate=AUTO) Long id; @Version protected int version; @ManyToOne Address address; @Basic String description; @OneToMany(targetEntity=com.acme.Order.class, mappedBy=quot;customerquot;) Collection orders = new Vector(); @ManyToMany(mappedBy=quot;customersquot;) Set<DeliveryService> serviceOptions = new HashSet(); public Customer() {} public Collection getOrders() { return orders; } public Set<DeliveryService> getServiceOptions() { Friday, February 13, 2009
  • 33. JPA Persistence Interfaces EntityManager – Interface to interact with persistence context. – @PersistenceContext EntityManagerFactory – Creates an EntityManager – @PersistenceUnit Friday, February 13, 2009
  • 34. Acquiring a Manager Injection in Stateless Bean @PersistenceContext public EntityManager em; OR @PersistenceContext(unitName=quot;orderquot;) EntityManager em; From Java Application EntityManagerFactory emf = Persistence.createEntityManagerFactory(quot;unit1quot;); EntityManager em = emf.createEntityManager(); Friday, February 13, 2009
  • 35. Spring 2 JPA Support org.springframework.orm.jpa package Contains subset of the JPA container JpaDaoSupport – similar to other DAO support classes like HibernateDaoSupport LocalEntityManagerFactoryBean – Provides resource bootstrapping for non-jndi lookups Friday, February 13, 2009
  • 36. Spring / JPA Approaches JpaDaoSupport Approach – Not preferred approach – Similar to HibernateDaoSupport – Requires Spring Configuration of the EntityManager Pure JPA Approach – Preferred approach – No spring references necessary in the code • with the exception of @Transactional 34 Friday, February 13, 2009
  • 37. Approach 2: Spring / Pure JPA Configuration Leverage the persistence.xml in classpath:/META-INF <bean id=quot;entityManagerFactoryquot; class=quot;org.springframework.orm.jpa.LocalEntityManagerFactoryBeanquot; > <property name=quot;persistenceUnitNamequot; value=quot;unit1quot;/> </bean> DAO with no Spring references, however it contains @PersistenceContext annotated EntityManager <bean id=quot;conferenceDaoquot; class=quot;com.codementor.jpa.domain.ConferenceDAOImplquot;/> Spring configuration which injects JPA annotationed EntityManager <bean class=quot;org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProces sor“ /> Friday, February 13, 2009
  • 38. Pure JPA Code Example: ConferenceDaoImpl package com.nfjs.jpa; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.transaction.annotation.Transactional; public class ConferenceDAOImpl implements ConferenceDAO { @PersistenceContext private EntityManager entityManager; public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } – ... 36 Friday, February 13, 2009
  • 39. Pure JPA Spring Configuration <bean id=quot;entityManagerFactoryquot; class=quot;org.springframework.orm.jpa.LocalEntityManagerFactoryBeanquot; > <property name=quot;persistenceUnitNamequot; value=quot;nfjsquot;/> </bean> <bean id=quot;conferenceDaoquot; class=quot;com.nfjs.jpa.ConferenceDAOImplquot;/> <bean class=quot;org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessorquot; /> </beans> 37 Friday, February 13, 2009
  • 40. No PU No Problem The LocalContainerEntityManagerFactoryBean can be configured with all Persistent Unit information. <bean id=quot;entityManagerFactoryquot; class=quot;org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBeanquot;> <property name=quot;dataSourcequot; ref=quot;dataSourcequot;/> <property name=quot;jpaVendorAdapterquot;> <bean class=quot;org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapterquot;> <property name=quot;showSqlquot; value=quot;truequot;/> <property name=quot;generateDdlquot; value=quot;truequot;/> <property name=quot;databasePlatformquot; value=quot;org.hibernate.dialect.HSQLDialectquot;/> </bean> </property> </bean> Friday, February 13, 2009
  • 41. Transactions XML Configuration <tx:annotation-driven /> Annotation @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) Public void doSomething() { ** transaction manger bean id must be transactionManger or configured with the xml configuration above. Friday, February 13, 2009
  • 42. Test JPA with Spring public class SpeakerDAOTest extends AbstractJpaTests { private SpeakerDAO speakerDao; public void setSpeakerDao(SpeakerDAO speakerDao) { this.speakerDao = speakerDao; } protected String[] getConfigLocations() { return new String[] {quot;classpath:/jpaContext.xmlquot;}; } protected void onSetUpInTransaction() throws Exception { jdbcTemplate.execute( quot;insert into speaker (id, name, company) values (1, 'Ken', 'CodeMentor')quot;); Friday, February 13, 2009
  • 43. AbstractJpaTests Benefits getConfigLocations () – Separates test from production configuration – Allows for multiple configurations Injected Dependencies By Type – field references Every Test – Starts a Transactions – Rolls back Transaction Leverage jdbcTemplate for SQL checks Friday, February 13, 2009
  • 46. Spring 2.5 MVC Annotations @Controller – Stereotype used to “Controller” of MVC – Scanned for RequestMappings @RequestMapping – Annotates a handler method for a request – Very flexible @RequestParam – Annotates that a method parameter should be bound to a web request parameter @SessionAttributes – Marks session attributes that a handler uses Friday, February 13, 2009
  • 47. New Controller Issues Doesn’t implement an Interface Multiple request mappings High degree of flexibility 45 Friday, February 13, 2009
  • 48. Advantages of Controller Interfaces 46 Friday, February 13, 2009
  • 49. Advantages of Controller Interfaces It looks like your trying to build a controller 46 Friday, February 13, 2009
  • 50. Advantages of Controller Interfaces 46 Friday, February 13, 2009
  • 51. A World Without Rules Return Type? Parameters? 47 Friday, February 13, 2009
  • 52. @RequestMapping - Extreme Flexibility Parameters can be – Request / response / session – WebRequest – InputStream – OutputStream – @RequestParam – +++ Return types – ModelAndView Object – Model Object – Map for exposing model – View Object – String which is a view name – Void… if method wrote the response content directly Friday, February 13, 2009
  • 53. Spring 2.5 Controller Example @Controller public class ConfController { @Autowired private confDB confDB; @RequestMapping(quot;/sessionListquot;) public String showSessionList(ModelMap model) { model.addAttribute(quot;sessionsquot;, this.confDB.getSessions()); return quot;sessionListquot;; } @RequestMapping(quot;/speakerImagequot;) public void streamSpeakerImage(@RequestParam(quot;namequot;) String name, OutputStream outputStream) throws IOException { this.confDB.getSpeakerImage(name,outputStream); } @RequestMapping(quot;/clearDatabasequot;) public String clearDB() { this.confDB.clear(); return quot;redirect:sessionListquot;; } } Friday, February 13, 2009
  • 54. Spring MVC By Convention Conventions: hotel = HotelController GET /hotel/list list = method View selected from request path Added to Model 50 Friday, February 13, 2009
  • 55. Multi-Action Convention /hotel/index /hotel/show /hotel/list 51 Friday, February 13, 2009
  • 56. Working With Parameters /hotel/show?id=42 52 Friday, February 13, 2009
  • 57. @PathVariable - RESTFUL GET /owner/show/2 53 Friday, February 13, 2009
  • 58. Submitting Forms 54 Friday, February 13, 2009
  • 60. Summary - ADD I’m sorry... Were we talking about something... Oh Yeah... ADD Friday, February 13, 2009
  • 61. Summary  @nnotations  They @re every where!  They c@n incre@se productivity Friday, February 13, 2009
  • 62. Questions  Please Fill Out Surveys kensipe@gmail.com twitter: @kensipe kensipe.blogspot.com Friday, February 13, 2009