62
Spring - ADD Developer Annotated Driven Development Friday, February 13, 2009

Spring 3 Annotated Development

  • Upload
    kensipe

  • View
    34.398

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Spring 3 Annotated Development

Spring - ADD Developer

Annotated Driven Development

Friday, February 13, 2009

Page 2: Spring 3 Annotated Development

About Speaker

Speaker @ JavaOne, NFJS, Devcon, BorconSun Certified Java 2 Architect.Instructor for VisiBroker for Java, OOAD, Rational Rose, and Java Development.

JBoss Certified Developer

Friday, February 13, 2009

Page 3: Spring 3 Annotated Development

Agenda

Annotations and the MV Spring 2.5/3 Annotations

– Spring Business TierSpring Data TierSpring MVC TierSummary

Friday, February 13, 2009

Page 4: Spring 3 Annotated Development

Industry Forces

Annotations– EJB 3.X

– JSR-250 Common Annotations– JSR-299 Web Beans

Guice / SEAMXML... way too much XML

Friday, February 13, 2009

Page 5: Spring 3 Annotated Development

Industry Move to Annotations

5

Friday, February 13, 2009

Page 6: Spring 3 Annotated Development

Commons Annotation

6

@Resource

@PostConstruct@PreDestroy

Friday, February 13, 2009

Page 7: Spring 3 Annotated Development

EJB Annotation

@Resource

@PostConstruct@PreDestroy

Commons

Friday, February 13, 2009

Page 8: Spring 3 Annotated Development

EJB Annotation

7

@Resource

@PostConstruct@PreDestroy

@EJBCommons

@Stateless

@Stateful

@Init

@MessageDriven

@Home

@Inject@Interceptor

@MethodPermissions

@SecurityRoles

@RunAs

@TransactionAttribute@TransactionManagement

Friday, February 13, 2009

Page 9: Spring 3 Annotated Development

JPA Annotation

8

@Resource

@PostConstruct@PreDestroy

@EJB

Commons

@Stateless

@Stateful@Init@MessageDriven

@Home

@Inject@Interceptor

@MethodPermissions

@SecurityRoles

@RunAs

@TransactionAttribute@TransactionManagement

EJB

Friday, February 13, 2009

Page 10: Spring 3 Annotated Development

JPA Annotation

8

@Resource

@PostConstruct@PreDestroy

@EJB

Commons

@Stateless

@Stateful@Init@MessageDriven

@Home

@Inject@Interceptor

@MethodPermissions

@SecurityRoles

@RunAs

@TransactionAttribute@TransactionManagement

EJB

@Entity

@Table

@Column

@GeneratedValue@JoinColumn

@Id

@EmbeddedId @Transient

@Version @Serialized

@ManyToOne@OneToOne

@OneToMany

@AssociationTable

@ManyToMany

@DisciminatorColumn

Friday, February 13, 2009

Page 11: Spring 3 Annotated Development

JPA Annotation

9

@Resource

@PostConstruct@PreDestroy

@EJB

Commons

@Stateless

@Stateful@Init@MessageDriven

@Home

@Inject@Interceptor

@MethodPermissions

@SecurityRoles

@RunAs

@TransactionAttribute@TransactionManagement

EJB

@Entity @Table@Column@GeneratedValue

@JoinColumn

@Id @EmbeddedId

@Transient

@Version@Serialized

@ManyToOne

@OneToOne@OneToMany

@AssociationTable

@ManyToMany

@DisciminatorColumn

JPA

Friday, February 13, 2009

Page 12: Spring 3 Annotated Development

Web Services

10

@Resource

@PostConstruct@PreDestroy

@EJB

@Stateless

@Stateful

@Init@MessageDriven

@Home

@Inject

@Interceptor

@MethodPermissions

@SecurityRoles@RunAs

@TransactionAttribute@TransactionManagement @Entity

@Table@Column

@GeneratedValue@JoinColumn@Id

@EmbeddedId

@Transient

@Version@Serialized

@ManyToOne

@OneToOne

@OneToMany@AssociationTable

@ManyToMany

@DisciminatorColumn@WebServiceRef

@WebServiceRefs

Friday, February 13, 2009

Page 13: Spring 3 Annotated Development

Web Beans

11

@Resource

@PostConstruct@PreDestroy

@EJB

@Stateless

@Stateful

@Init@MessageDriven

@Home

@Inject

@Interceptor

@MethodPermissions

@SecurityRoles@RunAs

@TransactionAttribute@TransactionManagement @Entity

@Table@Column

@GeneratedValue@JoinColumn@Id

@EmbeddedId

@Transient

@Version@Serialized

@ManyToOne

@OneToOne

@OneToMany@AssociationTable

@ManyToMany

@DisciminatorColumn@WebServiceRef@WebServiceRefs

@New

@In@Out

@Model@SessionScoped@Current@LoggedIn@Produces@Interceptor@Secure@Decorator@Synchronous@Asynchronous

Friday, February 13, 2009

Page 14: Spring 3 Annotated Development

Servlet 3

12

@Resource

@PostConstruct@PreDestroy

@EJB

@Stateless

@Stateful

@Init@MessageDriven

@Home

@Inject

@Interceptor

@MethodPermissions

@SecurityRoles@RunAs

@TransactionAttribute@TransactionManagement @Entity

@Table@Column

@GeneratedValue@JoinColumn@Id

@EmbeddedId

@Transient

@Version@Serialized

@ManyToOne

@OneToOne

@OneToMany@AssociationTable

@ManyToMany

@DisciminatorColumn@WebServiceRef@WebServiceRefs

@New

@In@Out

@Model@SessionScoped

@Current@LoggedIn

@Produces@Interceptor

@Secure@Decorator

@Synchronous@Asynchronous

@WebServlet@ServletFilter@InitParam@WebServletContextListenter

Friday, February 13, 2009

Page 15: Spring 3 Annotated Development

JSR 303: Bean Validation

13

@Resource

@PostConstruct@PreDestroy

@EJB

@Stateless

@Stateful

@Init@MessageDriven

@Home

@Inject

@Interceptor

@MethodPermissions

@SecurityRoles@RunAs

@TransactionAttribute@TransactionManagement @Entity

@Table@Column

@GeneratedValue@JoinColumn@Id

@EmbeddedId

@Transient

@Version@Serialized

@ManyToOne

@OneToOne

@OneToMany@AssociationTable

@ManyToMany

@DisciminatorColumn@WebServiceRef@WebServiceRefs

@New

@In@Out

@Model@SessionScoped

@Current@LoggedIn

@Produces@Interceptor

@Secure@Decorator

@Synchronous@Asynchronous

@WebServlet@ServletFilter

@InitParam@WebServletContextListenter

@ConstraintValidator@NotNull

@Length@Min@Pattern@Size@Valid@NotEmpty

Friday, February 13, 2009

Page 16: Spring 3 Annotated Development

JSR 303: Bean Validation

14

@Resource

@PostConstruct@PreDestroy

@EJB

@Stateless

@Stateful

@Init@MessageDriven

@Home

@Inject

@Interceptor

@MethodPermissions

@SecurityRoles@RunAs

@TransactionAttribute@TransactionManagement @Entity

@Table@Column

@GeneratedValue@JoinColumn@Id

@EmbeddedId

@Transient

@Version@Serialized

@ManyToOne

@OneToOne

@OneToMany@AssociationTable

@ManyToMany

@DisciminatorColumn@WebServiceRef@WebServiceRefs

@New

@In@Out

@Model@SessionScoped

@Current@LoggedIn

@Produces@Interceptor

@Secure@Decorator

@Synchronous@Asynchronous

@WebServlet@ServletFilter

@InitParam@WebServletContextListenter

@ConstraintValidator

@NotNull

@Length

@Min @Pattern

@Size @Valid

@NotEmpty

Friday, February 13, 2009

Page 17: Spring 3 Annotated Development

JSR-299 Context and DI for Java

@NonBinding@Named

@Stereotype@Interceptor

@InterceptorBindingType@Decorator@Decorates

@ScopeType@ApplicationScoped

@RequestScoped@SessionScoped@ConverationScoped

@Dependent@BindingType

@DeploymentType@Produces@Disposes

@Specializes15

@Realizes@Initializer

@New@Current

@Production@Standard@Obtains

@Initialized@Deployed

@Observes@IfExists@Asynchronously

@AfterTransactionCompletion@AfterTransactionFailure

@AfterTransactionSuccess@BeforeTransactionCompletion@Fires

@Model

Friday, February 13, 2009

Page 18: Spring 3 Annotated Development

Annotation Frustrations

Not MentionedJMX 2.0JAX-RSJUnit 4 / TestNGAOP frameworksSpring

Friday, February 13, 2009

Page 19: Spring 3 Annotated Development

Spring Annotations

Friday, February 13, 2009

Page 20: Spring 3 Annotated Development

Spring 3 - Annotation Support

JSR 250 - @PostConstruct, @Resource…JAX-WS 2.0’s - @WebServiceRefEJB 3.0 - @EJBMVC annotations - @RequestParam, @RequestMapping…Test Enhancements - Junit 4.4 and TestNGStereotypes - @Component, @Controller…Spring enhancements - @Autowired, AOP - @Configurable

Friday, February 13, 2009

Page 21: Spring 3 Annotated Development

Spring Annotations

Spring 2.x Data Access Annotations

Spring 2.x AspectsSpring 2.5 Context AnnotationsSpring 2.5 StereotypesSpring 2.5 Factory AnnotationsSpring 2.5 MVC AnnotationsSpring 3.0 REST

Friday, February 13, 2009

Page 22: Spring 3 Annotated Development

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

Page 23: Spring 3 Annotated Development

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

Page 24: Spring 3 Annotated Development

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

Page 25: Spring 3 Annotated Development

Constructor

Setter

Field

23

Types of Injections

Friday, February 13, 2009

Page 26: Spring 3 Annotated Development

configuration method

with any number of arguments

24

New Injection Type

Friday, February 13, 2009

Page 27: Spring 3 Annotated Development

Let me Qualify that

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

Or@Autowiredpublic void init(@Qualifier(“xyzNAme”) DataSource dataSource, Object2 obj)

{…}

Friday, February 13, 2009

Page 28: Spring 3 Annotated Development

DEMO

Friday, February 13, 2009

Page 29: Spring 3 Annotated Development

Spring / JPA

Friday, February 13, 2009

Page 30: Spring 3 Annotated Development

JPA - Specification

PackagingEntitiesEntity OperationsQueriesMetadataLife-cycle ModelCallbacks

Friday, February 13, 2009

Page 31: Spring 3 Annotated Development

Persistence.xml

In the classpath under the META-INF directory.

<persistence-unit name="unit1" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.hbm2ddl.auto" value="create"/> <property name="hibernate.ejb.autodetection" value="class"/> <property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost:1234/employee"/> <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/> <property name="hibernate.connection.username" value="sa"/> <property name="hibernate.connection.password" value=""/> </properties> </persistence-unit></persistence>

Friday, February 13, 2009

Page 32: Spring 3 Annotated Development

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="customer") Collection orders = new Vector();

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

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

Friday, February 13, 2009

Page 33: Spring 3 Annotated Development

JPA Persistence Interfaces

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

EntityManagerFactory– Creates an EntityManager– @PersistenceUnit

Friday, February 13, 2009

Page 34: Spring 3 Annotated Development

Acquiring a Manager

Injection in Stateless Bean

@PersistenceContext

public EntityManager em;

OR @PersistenceContext(unitName="order") EntityManager em;

From Java Application EntityManagerFactory emf =

Persistence.createEntityManagerFactory("unit1");

EntityManager em = emf.createEntityManager();

Friday, February 13, 2009

Page 35: Spring 3 Annotated Development

Spring 2 JPA Support

org.springframework.orm.jpa packageContains subset of the JPA containerJpaDaoSupport

– similar to other DAO support classes like HibernateDaoSupport

LocalEntityManagerFactoryBean– Provides resource bootstrapping for non-jndi lookups

Friday, February 13, 2009

Page 36: Spring 3 Annotated Development

Spring / JPA Approaches

JpaDaoSupport Approach– Not preferred approach– Similar to HibernateDaoSupport– Requires Spring Configuration of the

EntityManagerPure JPA Approach

– Preferred approach– No spring references necessary in the code

• with the exception of @Transactional

34

Friday, February 13, 2009

Page 37: Spring 3 Annotated Development

Approach 2: Spring / Pure JPA Configuration

Leverage the persistence.xml in classpath:/META-INF<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" > <property name="persistenceUnitName" value="unit1"/> </bean>

DAO with no Spring references, however it contains @PersistenceContext annotated EntityManager

<bean id="conferenceDao" class="com.codementor.jpa.domain.ConferenceDAOImpl"/>

Spring configuration which injects JPA annotationed EntityManager

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor“ />

Friday, February 13, 2009

Page 38: Spring 3 Annotated Development

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

Page 39: Spring 3 Annotated Development

Pure JPA Spring Configuration

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" > <property name="persistenceUnitName" value="nfjs"/> </bean>

<bean id="conferenceDao" class="com.nfjs.jpa.ConferenceDAOImpl"/>

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

</beans>

37

Friday, February 13, 2009

Page 40: Spring 3 Annotated Development

No PU No Problem

The LocalContainerEntityManagerFactoryBean can be configured with all Persistent Unit information.

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

<property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true"/> <property name="generateDdl" value="true"/> <property name="databasePlatform"

value="org.hibernate.dialect.HSQLDialect"/> </bean> </property> </bean>

Friday, February 13, 2009

Page 41: Spring 3 Annotated Development

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

Page 42: Spring 3 Annotated Development

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[] {"classpath:/jpaContext.xml"}; }

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

Friday, February 13, 2009

Page 43: Spring 3 Annotated Development

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

Page 44: Spring 3 Annotated Development

DEMO

Friday, February 13, 2009

Page 45: Spring 3 Annotated Development

Spring MVC

Friday, February 13, 2009

Page 46: Spring 3 Annotated Development

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

Page 47: Spring 3 Annotated Development

Doesn’t implement an InterfaceMultiple request mappingsHigh degree of flexibility

45

New Controller Issues

Friday, February 13, 2009

Page 48: Spring 3 Annotated Development

46

Advantages of Controller Interfaces

Friday, February 13, 2009

Page 49: Spring 3 Annotated Development

46

It looks like your trying to build a

controller

Advantages of Controller Interfaces

Friday, February 13, 2009

Page 50: Spring 3 Annotated Development

46

Advantages of Controller Interfaces

Friday, February 13, 2009

Page 51: Spring 3 Annotated Development

Return Type?Parameters?

47

A World Without Rules

Friday, February 13, 2009

Page 52: Spring 3 Annotated Development

@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

Page 53: Spring 3 Annotated Development

Spring 2.5 Controller Example

@Controllerpublic class ConfController {

@Autowired private confDB confDB;

@RequestMapping("/sessionList") public String showSessionList(ModelMap model) { model.addAttribute("sessions", this.confDB.getSessions()); return "sessionList"; }

@RequestMapping("/speakerImage") public void streamSpeakerImage(@RequestParam("name") String name,

OutputStream outputStream) throws IOException { this.confDB.getSpeakerImage(name,outputStream); }

@RequestMapping("/clearDatabase") public String clearDB() { this.confDB.clear(); return "redirect:sessionList"; }}

Friday, February 13, 2009

Page 54: Spring 3 Annotated Development

50

GET /hotel/list

View selectedfrom request path

Added to Model

Spring MVC By Convention

Conventions:hotel = HotelControllerlist = method

Friday, February 13, 2009

Page 55: Spring 3 Annotated Development

51

/hotel/index

/hotel/show

/hotel/list

Multi-Action Convention

Friday, February 13, 2009

Page 56: Spring 3 Annotated Development

52

/hotel/show?id=42

Working With Parameters

Friday, February 13, 2009

Page 57: Spring 3 Annotated Development

53

@PathVariable - RESTFUL

GET /owner/show/2

Friday, February 13, 2009

Page 58: Spring 3 Annotated Development

54

Submitting Forms

Friday, February 13, 2009

Page 59: Spring 3 Annotated Development

Demo

Friday, February 13, 2009

Page 60: Spring 3 Annotated Development

Summary - ADD

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

Oh Yeah...ADD

Friday, February 13, 2009

Page 61: Spring 3 Annotated Development

Summary

@nnotations

They @re every where!

They c@n incre@se productivity

Friday, February 13, 2009

Page 62: Spring 3 Annotated Development

Questions

Please Fill Out Surveys

[email protected]

twitter: @kensipe

kensipe.blogspot.com

Friday, February 13, 2009