Friday, March 22, 2013

Saving Java EE?

The recent InfoWorld article on TomEE possed the question "Can TomEE save Java EE?"
I want to say explicitly, we don't think Java EE needs saving. It's doing great.  Java EE 6 has gained huge traction with developers.  Java EE 7 is the first EE spec to be openly developed.  Something I'm talking about next week at Devoxx France.  Times have never been better for Java EE developers.
We do, however, want to change the old debates that have persisted over the last 10+ years.
Tomcat vs Java EE is tired and old.
As Tomcat commands so much of the market, the fact that we as developers can't agree on something so basic is a big problem. We made TomEE to address the section of people who have typically not been happy with the existing choices and graviate towards Tomcat instead.
As most these people using Tomcat do in fact use a number of Java EE technologies, the vision to reach them was pretty clear. Both Java EE and Tomcat needed to change.
  • In JavaEE-land, we (the JCP) created the Web Profile which is roughly half of the Full Profile. So, JavaEE shrunk, check.
  • Over at Apache, we took Tomcat and built it up to be a complete implementation of the Web Profile, got it certified and announced it as Apache TomEE. So, Tomcat grew.
In a very real sense TomEE is a middle ground. It represents both "sides" giving an inch and making a compromise.
As far as the Tomcat side of the compromises, we wanted to keep them as minimal as possible. We worked very hard to "go with the grain" of the Tomcat architecture, keep startup fast, keep memory low and overall keep it Tomcat.
As a result TomEE works out of the box with Tomcat-aware tools like Eclipse, NetBeans, Intellij, NewRelic, YourKit, JRebel etc. etc. This is also why we're seeing Cloud providers like Jelastic and ActiveState expand their Tomcat support to include TomEE. As well even traditional ISPs that focus on Tomcat, such as Metawerx have expanded their Tomcat support to include TomEE.
Whether or not the "Tomcat vs JavaEE" debate changes, the reality is both Tomcat and Java EE have changed.
While we don't consider ourselves the "savior of JavaEE", you can freely consider us the savior of time; time saved arguing and reinventing wheels.
It is very much the time to move on.

Wednesday, November 21, 2012

CDI, when to break out the EJBs


I sometimes joke that CDI is basically EJB 4.0. While that's obviously not true there is a considerable amount of similarity and that does create a bit of confusion for people. Here is some general information on EJB and CDI as they relate to each together.

EJB >= CDI

Note that EJBs are CDI beans and therefore have all the benefits of CDI. The reverse is not true (yet). So definitely don't get into the habit of thinking "EJB vs CDI" as that logic really translates to "EJB+CDI vs CDI", which is an odd equation.
In future versions of Java EE we'll be continuing to align them. What aligning means is allowing people to do what they already can do, just without the@Stateful@Stateless or @Singleton annotation at the top.

EJB and CDI in Implementation Terms

Ultimately, EJB and CDI share the same fundamental design of being proxied components. When you get a reference to an EJB or CDI bean, it isn't the real bean. Rather the object you are given is a fake (a proxy). When you invoke a method on this fake object, the call goes to the container who will send the call through interceptors, decorators, etc. as well as take care of any transaction or security checks. Once all that is done, the call finally goes to the real object and the result is passed back through the proxy to the caller.
The difference only comes in how the object to be invoked is resolved. By "resolved" we simply mean, where and how the container looks for the real instance to invoke.
In CDI the container looks in a "scope", which will basically be a hashmap that lives for a specific period of time (per request @RequestScoped, per HTTP Session @SessionScoped, per application @ApplicationScoped, JSF Conversation @ConversationScoped, or per your custom scope implementation).
In EJB the container looks also into a hashmap if the bean is of type @Stateful. An @Stateful bean can also use any of the above scope annotations causing it to live and die with all the other beans in the scope. In EJB @Stateful is essentially the "any scoped" bean. The @Stateless is basically an instance pool -- you get an instance from the pool for the duration of one invocation. The @Singleton is essentially @ApplicationScoped
So in a fundamental level, anything you can do with an "EJB" bean you should be able to do with a "CDI" bean. Under the covers it's awfully hard to tell them apart. All the plumbing is the same with the exception of how instances are resolved.
They aren't currently the same in terms of the services the container will offer when doing this proxying, but as I say we're working on it at the Java EE spec level.

Performance note

Disregard any "light" or "heavy" mental images you may have. That's all marketing. They have the same internal design for the most part. CDI instance resolution is perhaps a bit more complex because it is slightly more dynamic and contextual. EJB instance resolution is fairly static, dumb and simple by comparison.
I can tell you from an implementation perspective in TomEE, there's about zero performance difference between invoking an EJB vs invoking a CDI bean.

Default to POJOs, then CDI, then EJB

Of course don't use CDI or EJB when there is no benefit. Throw in CDI when you start to want injection, events, interceptors, decorators, lifecycle tracking and things like that. That's most the time.
Beyond those basics, there are a number of useful container services you only have the option to use if you make your CDI bean also an EJB by adding@Stateful@Stateless, or @Singleton on it.
Here's a short list of when I break out the EJBs.

Using JAX-WS

Exposing a JAX-WS @WebService. I'm lazy. When the @WebService is also an EJB, you don't have to list it and map it as a servlet in the web.xml file. That's work to me. Plus I get the option to use any of the other functionality mentioned below. So it's a no-brainer for me.
Available to @Stateless and @Singleton only.

Using JAX-RS

Exposing a JAX-RS resource via @Path. I'm still lazy. When the RESTful service is also an EJB, again you get automatic discovery and don't have to add it to a JAX-RS Application subclass or anything like that. Plus I can expose the exact same bean as an @WebService if I want to or use any of the great functionality mentioned below.
Available to @Stateless and @Singleton only.

Startup logic

Load on startup via @Startup. There is currently no equivalent to this in CDI. Somehow we missed adding something like an AfterStartup event in the container lifecycle. Had we done this, you simply could have had an @ApplicationScoped bean that listened for it and that would be effectively the same as an @Singleton with @Startup. It's on the list for CDI 1.1.
Available to @Singleton only.

Working in Parallel

@Asynchronous method invocation. Starting threads is a no-no in any server-side environment. Having too many threads is a serious performance killer. This annotation allows you to parallelize things you do using the container's thread pool. This is awesome.
Available to @Stateful@Stateless and @Singleton.

Scheduling work

@Schedule or ScheduleExpression is basically a cron or Quartz functionality. Also very awesome. Most containers just use Quartz under the covers for this. Most people don't know, however, that scheduling work in Java EE is transactional! If you update a database then schedule some work and one of them fails, both will automatically cleaned up. If the EntityManager persist call fails or there is a problem flushing, there is no need to un-schedule the work. Yay, transactions.
Available to @Stateless and @Singleton only.

Using EntityManagers in a JTA transaction

The above note on transactions of course requires you to use a JTA managed EntityManager. You can use them with plain "CDI", but without the container-managed transactions it can get really monotonous duplicating the UserTransaction commit/rollback logic.
Available to all Java EE components including CDI, JSF @ManagedBean@WebServlet@WebListener@WebFilter, etc. The@TransactionAttribute annotation, however, is available to @Stateful@Stateless and @Singleton only.

Keeping JTA managed EntityManager

The EXTENDED managed EntityManager allows you to keep an EntityManager open between JTA transactions and not lose the cached data. Good feature for the right time and place. Use responsibly :)
Available to @Stateful only.

Easy synchronization

When you need synchronization, the @Lock(READ) and @Lock(WRITE) annotations are pretty excellent. It allows you to get concurrent access management for free. Skip all the ReentrantReadWriteLock plumbing. In the same bucket is @AccessTimeout, which allows you to say how long a thread should wait to get access to the bean instance before giving up.
Available to @Singleton beans only.

Thursday, November 15, 2012

Meta-Annotations


Meta-Annotations

Meta-Annotations are an experiment in annotation inheritance, abstraction and encapsulation with a Java SE mindset
A meta-annotation is any annotation class annotated with @Metatype. The other annotations used on the meta-annotation become part of its definition. If any of those annotations happen to also be meta-annotations, they are unrolled as well and their annotations become part of the definition.

@Metatype

The recursion that is the meta-annotation concept only happens when an annotation is marked as a @javax.annotation.Metatype.
When @Metatype is seen the basic contract is "carry the surrounding annotations forward". When a class, method or other target uses an annotation annotated with @Metatype the annotations on that annotation are "unrolled" or carried forward and effectively placed on that class, method or other target as if they were explicitly declared.
If any of the annotations that are carried forward also are annotated with @Metatype the recursion continues. The result is a simple algorithm or design pattern that provides inheritance or reuse in a way that is not specific to any domain, API, or specification.
APIs and specifications can choose to formally adopt annotation reuse in this fashion, but the core concept and implementations of@Metatype do not need to be expanded to support these APIs or specifications.
The simple elegance of this not being domain specific is that it could be used to combine several annotations from different specifications into one reusable annotation. Say JAX-RS @PathParam("id") with Bean Validation @NotNull to create a new annotation called @ValidId.

Creating Meta-Annotations

If the annotation in question can be applied to ElementType.ANNOTATION_TYPE or ElementType.TYPE, creating a meta-annotation version of it is quite easy.
@TransactionManagement(TransactionManagementType.CONTAINER)
@Metatype
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ContainerManagedTransactions {
}
When the annotation in question cannot be applied to ElementType.ANNOTATION_TYPE or ElementType.TYPE, things get interesting. This is where meta-annotations depart from things like @Stereotype. The goal of meta-annotations is to be completely generic and not specific to any one domain or API. A such, you cannot really require all existing APIs change to allow for meta-annotations. The goal is that meta-annotations can be used generically and do not need to be "designed" into an API.
To allow annotations that apply to FIELDMETHODPARAMETERCONSTRUCTORLOCAL_VARIABLE, or PACKAGE, as well as any other location where annotations may be applied in the future a compromise is made.
import javax.ejb.Schedule;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Metatype
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)

public @interface Daily {
    public static class $ {

        @Daily
        @Schedule(second = "0", minute = "0", hour = "0", month = "*", dayOfWeek = "*", year = "*")
        public void method() {
        }
    }
}
An inner class named $. This is enough to bind together the @Daily and @Schedule in the context to which they both apply.
Ugly but effective. Alternate proposals welcome.
The above is considered the public API portion of the meta-annotation concept.
The concept itself is born out of standards based systems like EJB and CDI where annotation processing is invisible to the application itself. In those settings the above is enough and no additional APIs would be needed to support meta-annotations in standard APIs.

Under the covers

The "guts" of this particular implementation is designed to look and feel as much like the reflection API as possible. Obviously, with VM level control, you could do much better. A clean Java SE API might be just what is needed and its very possible that meta-annotations should really be a Java SE concept.
Here's a glimpse as to how things can look under the covers:
final java.lang.reflect.AnnotatedElement annotated = new org.metatype.MetaAnnotatedClass(Triangle.class);
assertNotNull(annotated);

assertTrue(annotated.isAnnotationPresent(Color.class));
assertTrue(annotated.getAnnotation(Color.class) != null);
assertTrue(!contains(Color.class, annotated.getDeclaredAnnotations()));
assertTrue(contains(Color.class, annotated.getAnnotations()));
assertEquals("red", annotated.getAnnotation(Color.class).value());

assertTrue(annotated.isAnnotationPresent(Red.class));
assertTrue(annotated.getAnnotation(Red.class) != null);
assertTrue(!contains(Red.class, annotated.getDeclaredAnnotations()));
assertTrue(contains(Red.class, annotated.getAnnotations()));

assertTrue(annotated.isAnnotationPresent(Crimson.class));
assertTrue(annotated.getAnnotation(Crimson.class) != null);
assertTrue(contains(Crimson.class, annotated.getDeclaredAnnotations()));
assertTrue(contains(Crimson.class, annotated.getAnnotations()));
The application classes would look like so:
@Crimson
// -> @Red -> @Color
public static class Triangle {

}

@Metatype
@Color("red")
// one level deep
@Target(value = {TYPE})
@Retention(value = RUNTIME)
public static @interface Red {
}

@Metatype
@Red
// two levels deep
@Target(value = {TYPE})
@Retention(value = RUNTIME)
public static @interface Crimson {
}

Best Practices
It is recommended to have an api package or some other package where "approved' annotations are defined and to prohibit usage of the non-meta versions of those annotations. All the real configuration will then be centralized in the api package and changes to the values of those annotations will be localized to that package and automatically be reflected throughout the application.
An interesting side-effect of this approach is that if the api package where the meta-annotation definitions exist is kept in a separate jar as well, then one can effectively change the configuration of an entire application by simply replacing the api jar.

Future concepts

XML Overriding

The unrolling of meta-annotations happens under the covers. In that same vein, so could the concept of overriding.
The above @Red annotation might theoretically be overridden via xml as follows:

<org.superbiz.api.Red>
  <org.superbiz.api.Color value="dark red"/>
</org.superbiz.api.Red>
Or take more complex meta-annotation definition like the following:
package org.superbiz.corn.meta.api;

import javax.ejb.Schedule;
import javax.ejb.Schedules;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Metatype
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)

public @interface PlantingTime {
    public static interface $ {

        @PlantingTime
        @Schedules({
                @Schedule(month = "5", dayOfMonth = "20-Last", minute = "0", hour = "8"),
                @Schedule(month = "6", dayOfMonth = "1-10", minute = "0", hour = "8")
        })
        public void method();
    }
}
This might theoretically be overridden as:

<org.superbiz.corn.meta.api.PlantingTime>
  <javax.ejb.Schedules>
    <value>
      <javax.ejb.Schedule month="5" dayOfMonth="15-Last" minute="30" hour="5"/>
      <javax.ejb.Schedule month="6" dayOfMonth="1-15" minute="30" hour="5"/>
    </value>
  </javax.ejb.Schedules>
</org.superbiz.corn.meta.api.PlantingTime>

Merging or Aggregating definitions
Certain annotations take lists and are designed to be multiples. In the current definition of meta-annotations, the following is illegal.
@RolesAllowed({"Administrator", "SuperUser"})
@Metatype
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Admins {
}

@RolesAllowed({"Employee", "User"})
@Metatype
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Users {
}


public static class MyBean {

    @Admin
    @User
    public void doSomething() {
        // ...
    }
}
Here the @Admin and @User annotation each resolve to @RolesAllowed. Since only one @RolesAllowed annotation is allowed on the method per the Java language specification, this results in an error.
The intention is clear however and aggregating metadata together in this way is natural.
A theoretical way to support something like this is with an annotation to describe that this aggregation is intended and desired. Note the addition of the theoretical @Merge annotation.
@RolesAllowed({"Administrator", "SuperUser"})
@Metatype
@Merge
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Admins {
}

@RolesAllowed({"Employee", "User"})
@Metatype
@Merge
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Users {
}


public static class MyBean {

    @Admin
    @User
    public void doSomething() {
        // ...
    }
}
A new @RolesAllowed annotation would be created containing the list {"Administrator", "SuperUser", "Employee", "User"} and that would represent the final @RolesAllowed usage for the doSomething() method.

Friday, September 30, 2011

JavaOne 2011 schedule

JavaOne is next week and as usual I will be there.  I'm a bit busier than usual this year, but as always I'm more than happy to get together with anyone.  In fact it's my favorite part of JavaOne, so please do reach out.

Here's my speaking schedule:


Session ID: 23166
Session Title: Meet the Experts: EJB 3.2 Expert Group
Venue / Room: Hilton San Francisco - Imperial Ballroom A
Date and Time: 10/3/11, 21:00 - 21:45

Session ID: 25244
Session Title: EJB with Meta-annotations
Venue / Room: Parc 55 - Powell I/II-
Date and Time: 10/4/11, 17:30 - 18:15

Session ID: 23423
Session Title: The Road to Java EE 7: Is It All About the Cloud?
Venue / Room: Hilton San Francisco - Imperial Ballroom A
Date and Time: 10/5/11, 11:30 - 12:30

Session ID: 25209
Session Title: Fun with EJB 3.1 and OpenEJB
Venue / Room: Hilton San Francisco - Golden Gate 3/4/5
Date and Time: 10/5/11, 13:00 - 14:00

Session ID: 19941
Session Title: CDI Today and Tomorrow
Venue / Room: Hilton San Francisco - Imperial Ballroom A
Date and Time: 10/6/11, 12:30 - 13:30

Session ID: 23680
Session Title: Apache TomEE Java EE 6 Web Profile
Venue / Room: Hilton San Francisco - Golden Gate 3/4/5
Date and Time: 10/6/11, 11:00 - 12:00

Thursday, April 7, 2011

Final is my favorite Java keyword

Final is my favorite keyword and modifier in Java.  For fields, love it even more than private.  Think about it, you don't even need private on your field if it's final.  Not with a truly non-mutable data type at least, so collections and things of that nature excluded of course.

In fact I wish final was the default modifier for all my fields, variables, and parameters.  You should have to announce your intention to overwrite an already initialized object reference.  After years, I find it is a rarity.

There is nothing worse that digging through a large 500 line function and not being able to see what is changed and where.  Even more frustrating when you go to extract a method from said too-large codeblock and cannot do so easily because of the sprawled out variable declarations and initializations and the occasional "I like this variable name so I'll reuse the reference" laziness.

The trouble is it looks so terrible when used properly, which should be almost everywhere!  It looks pretty satisfying on fields, but over all parameters and variables it gets to be a little much.  It can actually make it harder to find the non-final object references.  And if you find one, was it intentional or just overlooked? Change it and find out I guess.

That is why one of my biggest wishes for the Java language is that final be the default and there to be a mutable or similar keyword for the handful of times you need it.  It would be an excellent aid to readers of your code, "watch out this thing is going to change." Compilers could even check to see if you have flagged something mutable and aren't actually mutating it.  That should be a compile error for variables and parameters, perhaps not for fields though.

Obviously we can't exactly do that ... not so directly.

We have some advantages now we didn't have when Java was created.  Annotations.  When Java was created there had to be long and deliberate thinking as to what the defaults should be.  Everyone would have to live with them and they'd last forever.  These days, however, a simple annotation or two on a Java source file could serve as a clean way to change such defaults in an obvious and documented way that can make the code in question far easier to read.  It would be syntactic sugar of course and that annotation and the defaults it specifies would compile away just as imports do.

A small bit of sugar with big payoff in ease and readability.

Friday, March 18, 2011

Reflection API gripes

java.lang.Method and java.lang.Constructor are strikingly close in concept. For all intents and purposes Constructors are little more than syntactic sugar. Yet there is no API acknowledgement of many their similarities.

Yes, they share some common interfaces and the same super class, but when you peal away the methods that are not accounted for by interfaces and superclasses, here's what you get:

java.lang.reflect.Constructor
public T newInstance(Object ... initargs)
public Annotation[][] getParameterAnnotations()
public Class[] getExceptionTypes()
public Class[] getParameterTypes()
public String toGenericString()
public Type[] getGenericExceptionTypes()
public Type[] getGenericParameterTypes()
public boolean isVarArgs()
java.lang.reflect.Method
public Object getDefaultValue()
public Object invoke(Object obj, Object... args)
public Class getReturnType()
public boolean isBridge()
public Type getGenericReturnType()
public Annotation[][] getParameterAnnotations()
public Class[] getExceptionTypes()
public Class[] getParameterTypes()
public String toGenericString()
public Type[] getGenericExceptionTypes()
public Type[] getGenericParameterTypes()
public boolean isVarArgs()
Of the methods, few are actually truly unique to that class type. Those would be the following methods

java.lang.reflect.Constructor
public T newInstance(Object ... initargs)
java.lang.reflect.Method
public Object getDefaultValue()
public Object invoke(Object obj, Object... args)
public Class getReturnType()
public boolean isBridge()
public Type getGenericReturnType()
A far smaller number, especially for Constructor. The remaining methods shared, but not accounted for in any superclass or interface, are:

Identical
public Annotation[][] getParameterAnnotations()
public Class[] getExceptionTypes()
public Class[] getParameterTypes()
public String toGenericString()
public Type[] getGenericExceptionTypes()
public Type[] getGenericParameterTypes()
public boolean isVarArgs()
These methods are just begging for an interface. Perhaps ParameterizedMember would be a good name?

Granted most Java development doesn't involve the reflection api, but those of us that do use it would really appreciate being thrown a bone. Especially with the growing amount of code and APIs that involve annotations. An interface similar to AnnotatedElement that can contain this critical getParameterAnnotations method would just be wonderful.

I'm quite certain there must have been some kind of debate. Likely one that ended in, "it's not really that important." Would love to hear from anyone involved.

I personally can't think of any downside to allowing us developers who deal with the guts of supporting annotation based APIs to get a little polymorphism in this are of the reflection API.

A bottle of my favorite rum to whomever can get this into Java 7.

Friday, October 1, 2010

EJB.next Connector/Bean API : JAX-RS and beyond

It isn't commonly known that MessageDrivenBeans (MDBs) are not directly tied to the Java Message Service (JMS). In fact, they are tied to the Java EE Connector Architecture. It's even less commonly known that MDBs are not necessarily asynchronous. It's really the Connector that drives the communication style.
Overall, it is a very cool model that does allow for some pretty impressive and standard extension to any compliant Java EE platform. It is, however, incredibly underused. With a few changes to the model, it could be made to support even things like JAX-RS. Let's break it down.
The touchpoints between the Connector and the MDB are the ActivationSpec/ActivationConfig and the MessageListener interface. Using a fictitious "Email" Connector idea, let's see how this looks.
EmailConsumer (MessageListener) interface*
package org.superemail.connector;

// other imports...
    
public interface EmailConsumer {
    public void receiveEmail(Properties headers, String body);
}
EmailAccountInfo (ActivationSpec) class
package org.superemail.connector;
    
/**
 * This class is basically an old-style JavaBean with get/set for each property
 */
public class EmailAccountInfo implements javax.resource.spi.ActivationSpec {

    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void validate() throws InvalidPropertyException {
    }
}
That's it for the Connector (aside from the Connector itself). I have left out a little detail on the ActivationSpec, we'll cover that later.
Now for the MDB's side of things. The MDB needs to implement the Connector's EmailConsumer interface and configure the Connector'sEmailAccountInfo JavaBean which is done via the activation-config tag of the ejb-jar.xml or via @ActivationConfigPropertyannotations in the @MessageDriven declaration.
@MessageDriven(activationConfig = 
        {@ActivationConfigProperty(
                propertyName = "address", 
                propertyValue = "dblevins@apache.org")
        })
public class EmailBean implements EmailConsumer {

    @PostConstruct
    public void init() {
    }

    public void receiveEmail(Properties headers, String body) {
        // do your thing!
    }
}
Done. Those are the basics. The Connector supplies a MessageListener interface and an ActivationConfig JavaBean, the MDB implements the interface and configures the JavaBean via the loosely-typed @ActivationConfigProperty.
There are a few things that prevent this model from reaching its true potential:
  • Metadata is loosely typed in the bean code
  • Only class-level metadata is allowed, not method-level
  • Requiring an interface can limit expressiveness
Let's see how life might look if we eliminate the JavaBean and allow the Connector to instead supply an annotation.
package org.superemail.connector;
    
@Target(TYPE)
@Retention(RUNTIME)
@javax.resource.annotation.ActivationSpec
public @interface EmailAccountInfo {
    String address();
}
Side Note: The original javax.resource.spi.ActivationSpec interface has a 'validate()' method on it to validate the JavaBean. A clear update to that part of the API would be to instead use the Bean Validation API.
Which gives us a bean that might look like this:
@MessageDriven
@EmailAccountInfo(address = "dblevins@apache.org")
public static class EmailBean implements EmailConsumer {

    @PostConstruct
    public void init() {
    }

    public void receiveEmail(Properties headers, String body) {
        // do your thing!
    }
}
Now we're getting somewhere!
Ok, let's get rid of that message listener interface and image our Email Connector uses a very JAX-RS inspired API for consuming emails. If you know a little JAX-RS you'll see where I'm going with this.
@MessageDriven
@EmailAccountInfo(address = "dblevins@apache.org")
public static class EmailBean {

    @PostConstruct
    public void init() {
    }

    @Deliver @Header("Subject: {subject}")
    public void receiveEmail(@HeaderParam("subject") String subject, @Body String body) {
        // do your thing!
    }
}
Pretty neat, huh?
Side note: For the rare few of you that speak Connector implementation, instead of giving your Resource Adapter a MessageEndpoint that is a proxy that only implements the MessageListener interface and the standard MessageEndpoint interface, the Container would instead give you an @LocalBean proxy that also implements MessageEndpoint. If you're thinking that an API like that would be great to use... imagine with the above changes you could make that API ... and use it in any compliant Java EE platform. Maybe even submit your own JSR if you came up with something great.
Truthfully speaking, it's the Connector who controls the lifecycle of the bean (MDB). The Connector API already allows for the Connector to say to the Container, "create me a bean" and "destroy this bean". So really, we don't need @MessageDriven anymore. Instead we can do this:
import javax.annotation.ManagedBean;

@ManagedBean
@EmailAccountInfo(address = "dblevins@apache.org")
public static class EmailBean {
 // ....
}
That's a little more modern and perhaps a bit clearer.
At this point, we have a generic API to hook arbitrary "Connectors" up to arbitrary "Beans" that are managed by a container. Were this the case when JAX-RS was created, they wouldn't have had to put so much effort into duplicating all the services that people who have managed beans expect: injection of resources, lifecycle callbacks, interceptors.
Summary: A few improvements to the expressiveness of the metadata passed between a Bean and its Connector could kick the MDB/Connector model into the mainstream as was the intention of the API from the beginning. New specifications could be created based on this model and be introduced incrementally as they are developed and needed.
The impact of fully opening up the Bean metadata to the Connector is quite deep and wide and likely not something that will scream at you immediately. Ask yourself, could something like the new EJB 3.1 @Schedule API have been done with a Connector/Bean model like this? To some extent probably it could. Certainly there already existed a few Quartz Connectors out there prior to the introduction of @Schedule.
Take a moment to daydream. What kind of Connectors could you create with this model?


UPDATE - Feb 7th, 2013

Save this proposal.  Without more voices it will be delayed till Java EE 8.  Let's not wait 4 years!  Take action and celebrate the Java Community Process openness by showing your support for including this in Java EE 7.  Act now.

VOTE AND COMMENT HERE http://java.net/jira/browse/EJB_SPEC-60