0% found this document useful (0 votes)
3 views

Annotation

The document discusses Java 1.5 Annotations and EJB 3.0, highlighting the evolution of Java specifications and the benefits of annotations for declarative programming. It emphasizes the improvements in EJB 3.0 over EJB 2.1, including reduced code complexity, support for inheritance and polymorphism, and the use of annotations for configuration. Additionally, it covers various types of annotations, their retention policies, and examples of their application in Java and JUnit testing.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Annotation

The document discusses Java 1.5 Annotations and EJB 3.0, highlighting the evolution of Java specifications and the benefits of annotations for declarative programming. It emphasizes the improvements in EJB 3.0 over EJB 2.1, including reduced code complexity, support for inheritance and polymorphism, and the use of annotations for configuration. Additionally, it covers various types of annotations, their retention policies, and examples of their application in Java and JUnit testing.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Java 1.

5 Annotations and
EJB 3.0

15 Sep 2006
Gordon R. Cameron
Ken H. Stevens
JBoss World 2006

What happens in Vegas…


…comes Back to Intelliware
Pairing at Conferences
This Presentation
Brought to you by…
FreeMind
RFC – Request for Comment
• RFC-97 Telnet 1971
• RFC-114 FTP 1971
• RFC-788 SMTP 1981
• RFC-918 POP 1984
• RFC-1866 HTML 1995
• RFC-1945 HTTP 1996
• Proprietary protocols died.
JSR – Java Specification Request
• JSR-127 Java Server Faces
• JSR-152 JSP 2.0
• JSR-175 Java 1.5
• JSR-153 EJB 2.1
• JSR-220 EJB 3
• JSR-244 Java EE 5
• JSR-250 Common Annotations
JSR-175 Java 1.5
Java 1.5 Annotations
• Annotations enable a declarative style of
programming.
• An annotation indicates that the declared
element should be processed in some
special way by a compiler, development
tool, deployment tool, or during runtime.
• 3 Levels of Retention: SOURCE, CLASS
(default), RUNTIME.
Annotation Example
class Child extends Parent {
@Override
public void doWork() {
//do something
}
}
EJB 3.0 Annotation Example
@Entity @Table(name = "PURCHASE_ORDER")
public class Order implements java.io.Serializable {
private int id;
private double total;
private Collection<LineItem> lineItems;

@Id @GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}

@OneToMany(
cascade = CascadeType.ALL,
fetch = FetchType.EAGER,
mappedBy="order")
public Collection<LineItem> getLineItems() {
return lineItems;
}
}
Java 1.4 Annotations: JavaDoc
• @deprecated JavaDoc is now deprecated.
Use Java 1.5 @Deprecated annotation
instead.
• It’s looking like XDoclet will be replaced by
Java 5 annotations…
• It’s safer to generate production artifacts
from compiler/IDE aware annotations than
from comments.
Annotation Consumers
• “Tools” Only require SOURCE retention.
E.g. compilers, digest generators.
• “Introspectors” require RUNTIME
retention. Loads annotated classes and
interfaces into the VM for introspection.
Annotation Declaration
• Types
– Normal Annotation
– Single Member Annotation
– Marker Annotation
• No exceptions
• No inheritance
• Methods return primitive types, String,
Class, enum types, annotation types, or
arrays of the preceding types
Normal Annotation
public @interface RequestForEnhancement {
int id();
int priority
String synopsis();
engineer() default "[unassigned]";
String date() default "[unimplemented]";
}
@RequestForEnhancement(
id = 2868724,
synopsis = "Provide time-travel functionality",
engineer = "Mr. Peabody"
) public static void travelThroughTime(Date destination) { ... }
Single Member Annotation
public @interface Copyright {
String value();
}

@Copyright("2006 Intelliware")
public class OscillationOverthruster { ... }
Marker Annotation
public @interface Preliminary { }

@Preliminary public class TimeTravel { ... }


Built-in Annotations
Java Annotations
• @Override
• @Deprecated
• @SupressWarnings
Meta-Annotations
• @Target
• @Retention
• @Inherited
Meta-Annotation Examples
@Target(METHOD)
@Retention(SOURCE)
public @interface Override {}

@Target({TYPE,FIELD,METHOD,PARAMETER,
CONSTRUCTOR,LOCAL_VARIABLE})
@Retention(value=SOURCE)
public @interface SuppressWarnings {…}
@Target values
• TYPE
• FIELD
• METHOD
• PARAMETER
• CONSTRUCTOR
• LOCAL_VARIABLE
• ANNOTATION_TYPE
• PACKAGE
JSR-250 Common Annotations
• @Generated
• @Resource, @PostConstruct,
@PreDestroy
• @RunAs, @RolesAllowed, @PermitAll,
@DenyAll
Junit 4 Annotations
import org.junit.Test;
import junit.framework.TestCase;

public class AdditionTest extends TestCase {


private int x = 1;
private int y = 1;

@Before protected void initializeX() {x = 1;}


@Before protected void initializeY() { y = 1;}
@After protected void {System.out.println(“tearing down…”);}
@Test public void addition() {
int z = x + y;
assertEquals(2, z);
}
}
More Junit 4 Annotations
private PrintStream systemErr;

// Call once before all test methods


@BeforeClass protected void redirectStderr() {
systemErr = System.err;
System.setErr(new PrintStream(new ByteArrayOutputStream()));
}

// Call once after all test methods


@AfterClass protected void tearDown() {
System.setErr(systemErr);
}

@Test(expected=ArithmeticException.class)
public void divideByZero() {
int n = 2 / 0;
}

@Test(timeout=500) public void sometimesThisTestTakesTooLongToRun() {…}

@Ignore public void testThatTakesTooLongTorun() {…}


JSR-153 EJB 2.1

On the outside…
EJB 2.1

On the inside…
EJB 2.1
• Too much code. 5 files per entity.
• Rigid components:
– Can’t test outside the container
– Can’t serialize
– Can’t detach / reattach
– No inheritance
– No polymorphism
• No interceptors for Session Beans and
Message-driven Beans – resulting in lots of
repeated code, or reflection tricks
Poor Entity Bean Puppy can’t leave his Container…
The King…
Hibernate Entity POJOs are free to roam…
They can be serialized, detached, and reattached.
And polymorphed…
However, it is proprietary.
Proprietary solutions…
• Hibernate 2
• XDoclet
• Spring
• Tapestry
• JBoss 3
• There’s no standards compliant layer to
allow you to swap these tools out.
JSR-220 EJB3
JSR-244 Java EE 5
Forged from the revolution started
by The King…
Hibernate 3 is EJB3 compliant
JBoss 4+ is JEE5 compliant
(via Hibernate 3)
EJB3 Entity Beans
• Standardized ORM. Allow swapping of persistance
provider.
• Persistance is declared in annotations or XML. You
decide. Most stuff defaulted.
• Lets you do Java stuff. Support for inheritance and
polymorphism
• Just POJOs. Can test outside of container. Can detach,
reattach, and serialize.
• Improvement of EJB QL: Adding inner and outer join,
bulk update and delete, subqueries, and group by.
• Extended Persistence Contexts that live beyond the
current transaction.
• Embedded objects.
EJB3 Session and Message Beans
• Way less code: Elimination of component
interfaces (EJBObject, EJBLocalObject,
Remote), less checked exceptions. No more
required callbacks. No Home interface. Not in
your face anymore.
• EJB references are declared in annotations
• Interceptors for Session Beans and Message-
driven Beans
• Environmental / JNDI dependencies replaced
with annotations, injection, classpath lookup
• Most behaviours defaulted
SessionBean Example
@Stateless
@Remote(Calculator.class)
public class CalculatorBean implements Calculator {
public int add(int x, int y) {
return x + y;
}
public int subtract(int x, int y) {
return x - y;
}
}

public class Client {


public static void main(String[] args) throws Exception {
InitialContext ctx = new InitialContext();
Calculator calculator = (Calculator) ctx.lookup("CalculatorBean/remote");
System.out.println("1 + 1 = " + calculator.add(1, 1));
System.out.println("1 - 1 = " + calculator.subtract(1, 1));
}
}
Dependency Injection
@EJB private Calculator calculator;

@Resource(mappedName="DefaultDS")
private javax.sql.DataSource ds;

@Resource javax.ejb.SessionContext ctx;


@Resource javax.ejb.TimerService timer;
@Resource javax.ejb.UserTransaction ut;
Transaction Attributes
@TransactionAttribute(TransactionAttribute
Type.REQUIRES_NEW)
public int add(int x, int y) {
return x + y;
}
Message Driven Bean Example
@MessageDriven(activationConfig = {
@ActivationConfigProperty(
propertyName="destinationType",
propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(
propertyName="destination",
propertyValue="queue/tutorial/example")
})
public class ExampleMDB implements MessageListener {
public void onMessage(Message recvMsg) {
System.out.println("----------------");
System.out.println("Received message");
System.out.println("----------------");
}
}
Interceptors
• Stateless session bean callbacks
• PostConstruct - is invoked when the bean is first created, after any dependency injection is done.
• PreDestroy - is invoked when the bean is removed from the pool or destroyed.
• Message-driven bean callbacks
• PostConstruct - is invoked when the bean is first created, after any dependency injection is done.
• PreDestroy - is invoked when the bean is removed from the pool or destroyed.
• Stateful session bean callbacks
• PostConstruct - is invoked when the bean is first created, after any dependency injection is done.
• PreDestroy - is invoked when the bean is removed from the pool or destroyed. It will happen before any
@Remove annotated method is invoked.
• PostActivate - is invoked when
• PrePassivate -
• Entity bean callbacks
• PrePersist - Is invoked right before the entity is created in the database. Will cascade to all entities to which this
operation is cascaded.
• PostPersist - Is invoked right after the entity is created in the database. Will cascade to all entities to which this
operation is cascaded.
• PreRemove - Is invoked right before the entity is deleted in the database. Will cascade to all entities to which this
operation is cascaded.
• PostRemove - Is invoked right after the entity is deleted in the database. Will cascade to all entities to which this
operation is cascaded.
• PreUpdate - Takes place right before the database is updated.
• PostUpdate - Takes place immediately after the database has been updated.
• PostLoad - Takes place right after data has been loaded from the database and associated with the entity
Interceptor Example
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception {
System.out.println("*** DefaultInterceptor intercepting " +
ctx.getMethod().getName());
try {
return ctx.proceed();
} finally {
System.out.println("*** DefaultInterceptor exiting");
}
}
// Annotations available for exclusions
// Class and method specific interceptors available as well.
JSR-127 Java Server Faces
What JSP was to ASP…

…JSF is to .NET
JSF Goals
• reusable UI toolkit for custom components
• simple data exchange
• UI state management
• event-driven
Built-in support for
• UI component state across requests
• Markup differences between different browsers
• Multi-page form processing
• Strongly typed events for server-side handlers
• Input validation & errors
• Automatic type conversion
• Helpful error / exception handling
• Navigation
Seam
• Built on EJB3 and JSF
• “Seamless” integration of presentation tier
to business tier
• Move web applications away from
stateless towards stateful
• Business-process oriented
• Designed from the ground up to be
testable.
Questions?
Java 1.5 Annotations

The affect Java 1.5 Annotations has had on

You might also like