Contexts & Dependency Injection for Java

CDI 2.0 Second Face to face meeting feedback

Posted by Antoine Sabot-Durand on Sep 29, 2015 | Comments

Last week we had our second CDI 2.0 Face to Face meeting in Paris (France). This is a summary of the point discussed and leads we’d like to follow. Of course each point we’ll lead to a proposal later and discussed on the mailing list.

Roadmap

CDI 2.0 is still planned for 1st half 2016. We’ll focus on new feature and SE support for this release.

CDI 2.1 should start after 2.0 release and focus Java EE 8 specific enhancement. We’ll probably focus a bit more on modularity since Java 9 will be around the corner giving us a better visibility of how anticipate its new module approach. Content of 2.1 will be defined in the coming weeks

CDI SE review

CDI bootstrap on Java SE is one of the feature released in our first early draft. The Java SE support needed extra work to be complete and we wanted to review the boot api included to see how it could be enhanced.

bootstrap API

We’d like to review the proposed bootstrap API to make it a bit richer and have the boot process in a specific class. The idea is to get inspiration from the new Weld Se bootstrap with a builder pattern (see Weld and WeldContainer classes) and the possibility to explicitly choose the implementation if multiple impl should be in classpath.

Context control

This feature seemed a bit risky to specify. We’d preferred an approach based on existing built-in scope: RequestScoped and an interceptor activating it for a given invocation and unactivating it just after . something like this:

@WithinRequest
public void doSomethigWithRequestScopedBeans() {
}

This could give users the possibility to start and stop a context without explicitly adding these methods in the SPI We also discussed the possibility to have a Conversation-like context activated thru a built-in scope.

Bean discovery mode

The new bootstrap api should prevent us to specify a new bean discovery mode since the builder api will contains a mean to deactivate bean discovery and create a synthetic bean archive by adding class and packages of beans.

Async event review

There was discussion about exceptions handling and the issues raised from mixing sync and async observers. So the leads we’d like to follow are the following

  • stop calling sync observer from fireAsync() (fire() is for @Observes and fireAsync() is for @ObservesAsync)

  • Remove FireAsyncException in favor of CompletionException since an exception during async events pipeline execution is noting more than that.

To sum it up:

Table 1. async and sync events rules
Event method @Observes notified @ObservesAsync notified

fire()

yes, in the same thread

no

fireAsync()

no

yes, in a different thread

CDI Lite

As you know, CDI lite is one of the expected features for CDI 2.0. Yet, adding it with the SE / EE split for 2.0 could bring a lot of glitches and could reveal itself a catastrophe without speaking of specific impl and TCK for it.

That’s why we choose to add it in the annexe of the spec as a proposal for a next CDI version. Implementation will be allowed to create their CDI lite version based on this subset of CDI features:

  • JSR 330 with CDI type resolution rules

  • CDI qualifiers usage

  • Producers and disposers

  • Programmatic lookup

  • @Singleton and @Dependent pseudo-scopes support

  • SE bootstrap

We choose not to include events and spi to keep the impl lite. Of course this could be change during our discussion.

AOP on producer and custom beans

The goal was to propose a solution to apply Interceptors and Decorators on produced beans or custom beans. For producers we also have the problem of applying interceptor binding only on some method and not on the whole class. We looked for a solution that could be used in both case and that was more an "advanced users" approach than an out of box one.

The idea is to provide a class or a built-in bean to help produced bean instances using AnnotatedType to allow override of annotation on instance class. This suppose the addition of AnnotatedTypeBuilder to the SPI to ease the use of building a synthetic AnnotatedType. This would follow the same idea than the Unmanaged class which provide a way to inject bean in a non bean (non managed) class.

That would give something like:

public class MyAdvancedProducerBean {

    public BeanInstanceBuilder<MyClass> bib = new BeanInstanceBuilder<>();

    @Produces
    @RequestScoped
    public MyClass produceTransactionalMyClass() {

        AnnotatedTypeBuilder<MyClass> atb = new AnnotatedTypeBuilder<>()
           .readFrom(MyClass.class)
           .addToMethod(MyClass.class.getMethod("performInTransaction")
            , new TransactionalLiteral());

        return bib.readFromType(atb.build())
            .build(); //instance of the bean with requested interceptors / decorators
    }

    public void disposeMyClass (@Disposes Myclass td) {

        bib.dispose(td);
    }

}

A similar mechanism could be used in the create() method of custom beans.

Conclusion

Of course, all these points will be described in more detail in coming proposal documents. You’ll only find here general ideas of what we like to propose.

We also worked on other points in Jira for clarification or fix. This will go to the mailing list.

This post will be updated with new information or clarification if needed.

CDI 2.0 first Face to face meeting feedback!

Posted by Antoine Sabot-Durand on Oct 20, 2014 | Comments

Last week we had the first CDI 2.0 Face to Face meeting in Brno (Czech Republic). Check what was discussed and the first CDI 2.0 orientations

Meeting Agenda

As you may know, CDI 2.0 project was launched only six weeks ago, so we are still in early discussion stage regarding CDI 2.0 design. Yet our workshop organisation was a good entry point to start going in more deep discussion. So we based our discussion on existing workshop documents. Here are the main decisions that came out from our discussion.

Parts introduction

Parts concept is not the most visible change we would introduce in CDI 2.0 but since it’s probably the one with more impact on spec organisation, we started with this point to know if we should go in that direction. That answer was yes. We also decided that each part would be independent from the other (i.e a bigger part wouldn’t depend from a smaller one but would integrate it) to solve API splitting issues. Having this principles accepted we talked about the possible parts and their content:

  • CDI Light: a lightweight version of CDI without Normal Scopes, Interceptors and Decorators that would allow proxy-free implementations. We worked on the API present in this Part, you can have a look to what we proposed on this branch

  • CDI Full: CDI as we know it today except for all the other spec integration (servlet, JSF, EJB, etc…​).

  • CDI Java EE : CDI full including integration with other specs

Events enhancement

The 2 main topics here were ordering and asynchronous events.

Asynchronous events.

The main idea was to adopt a different approach than the one in EJB today. Instead of using a @Asynchronous annotation and manage a Future<T> to deal with he end of asynchronous treatment, we looked for a way to provide callback to the event trigering.

The idea could be to add a fireAsync() method to the Event<T> and use Java 8 lambdas and add a functional interface like this :

@FunctionalInterface
public interface EventCallBack<T> {

    void doCallback(T callBack);
}

and use later like this

@Inject
Event<Payload> evt;


public void fireAsyncWithCallBack() {

    evt.fireAsync(new Payload(), callBack -> System.out.println("Job done”));
}

Off course this approach has to be more deeply investigate (we’ll do it on our coming event meeting) but it has a lot of advantages :

  • Introduce a more modern approach of async events processing like we have in other framework or technologies

  • Complete the EJB approach instead of duplicating it

  • Avoid asking Java EE EG to extract @Asynchronous form EJB to put it somewhere else (where?)

Events priority

Discussion on event priority was open some weeks ago. We tried to have a fresh look to the idea. The main point was about using @Priority annotation or not. The question is still not closed but we’re more in favor of the use of a value in @Observes annotation. This value would give the order of the observer (the lowest being the first). The main reason to choose this approach instead of @Priority is the fact that while being part of java common annotation (JSR 250) spec, @Priority is not present in Java SE. So using it would :

  • force us to ask for JSR 250 Maintenance release to allow priority on paramaters

  • add an extra dependency jar (for only one annotation) when using CDI Light in Java SE which seems against our "light" goal

The @Observes evolution evolution would give something like:

public void firstObserver(@Observes(1) Payload pl) {}

public void secondObserver(@Observes(2) Payload pl) {}

Priority value provided in javax.interceptor.Interceptor.Priority would be duplicated in CDI to avoid useless dependency on Interceptor spec while keeping the same approach / values. This ordering could be also used to order step in extensions.

Event Range

The idea behind event range would to provide a "scope" to events (i.e package, war, ear). It would prepare CDI event to become a server wide eventing system. The discussion came to the conclusion that while it’s rather easy to implement, it’s usage could be quite cumbersome. The idea was not discarded but we thought it was a good idea to check with community if the need was real.

Interceptors and Decorators (AOP) enhancement

There were a lot of discussions around enhancing interceptors and decorators. You’ll find the main topics below.

AOP on custom beans and producers

Conclusion was that it is doable but with certain limitations. Among them the fact that an interceptor on producer would be applied on all method of it (no obvious solution to target specifc methods).

We also discussed the syntax for binding interceptor to a produced bean. if you consider this code:

@Produces

@Loggable

public  Foo produceMap() {

    return new Foo();

}

@Loggable interceptor binding is bound to the method not the produced bean. We have to find an easy way to bind the interceptor to the produced bean. The only solution we found was to use a Stereotype with the interceptor binding and put it on the producer. Not a direct solution but rather elegant.

AOP on internal call vs self injection pattern

We already discussed about supporting AOP on call make in the same bean (calling intercepted B method from method A with interceptor triggering). After discussion, it seemed very difficult to introduce this new feature and AOP support on produced and custom beans at the same time. So the idea was to ease the use of self injection pattern, providing something like this.

public class MyBean {

  @Inject
  Self<MyBean> mySelf;

  @Loggable
  public methodB() {
    ...
  }

  public methodA() {
    mySelf.get().methodB();
  }
}

less elegant than having it directly on internal call but still useful.

Other AOP topics

We also discussed about the following topics:

  • relaunching the idea of supporting decorator without interface like it was requested in CDI-403 and before that in CDI-224.

  • standardise the partial bean feature from Deltaspike. For those who don’t know this feature an example can be found here.

Java SE support

We had a long discussion on Java SE support in CDI 2.0. To decide that we should just provide a class like this:

public class ContainerBoot {

    /**
     * Simple boot
     */
    static BeanManager initialize() {
      ...
    }

    /**
     * Boot with parameters
     */
    static BeanManager intialize(Map<?,?>) {
      ...
    }
    void shutdown() {}
}

Discussions are still going on on this topic.

SPI enhancement

Last but not least we also discussed about SPI enhancement. The main topic were:

  • Give the possibility to modify/register beans at runtime. The majority of present people were against this new feature. The ones in favor obtained that the door wouldn’t be closed now and that the community would be consulted to see if this need was "real". So we’ll be back on this feature and if you want to see it, stay tune to give it your support when we’ll ask for it.

  • Add SPI to activate/deactivate contexts. Right now built-in context cannot be activated / deactivated by third parties, forcing them to create their own implementation of such contexts instead of using the one provided by their implementation. This small modification will greatly ease CDI advanced integration in other spec or frameworks.

  • Add helpers to create CDI meta-data. Today it’s not very convenient to create an AnnotatedType or a custom Bean. We decided to explore the introduction of helpers inspired by Deltaspike Builders. They would be provided by lifecycle event

Conclusion

Here are the main topics we discussed during these 2 days. Other small feature will came to JIRA later. At this point there was only orientation and no final decision on any subject. So the door is still open for these as well as new feature. So don’t hesitate to give your advice andv your contribution to our workshop or Jira server.

CDI EG meeting 12/16/2013 notes on CDI 1.2

Posted by Antoine Sabot-Durand on Dec 16, 2013 | Comments

The following people assisted this meeting :

  • Mark Struberg (ms)

  • Joseph Bergmark(jb)

  • Jozef Hartinger (jh)

  • Martin Kouba (mk)

  • JJ Snyder (jj)

  • Phil Zampino (pz)

  • Antoine Sabot-Durand (asd)

Proposed Agenda

The following agenda was proposed

  1. Discussion on the last ticket pending : CDI-395 Public fields in extensions should not be allowed

  2. Last second ticket

  3. Next step for the MR.

Discussion on CDI-395

We were waiting on implementation feedback on this point. jh told us that there was too much risk to create retro-compatibility issues. So it was decided to remove CDI-395 from MR.

Last minute issues

Jira Description Decision Note

CDI-408

bean-discovery-mode="annotated" and Producers/Observers in @Dependent beans

in MR

CDI-410

@RequestScoped Javadoc outdated

in MR

CDI-388

Session bean specialization example is not valid

in MR

CDI-376

BeanManager#getProducerFactory return type differs between API and spec

in MR

CDI-411

CDI conversation activation conflicts with the Servlet spec

Pending

needs some test before decicing if we can include it in MR. Test leaded by jh

Next Step

The list is now closed (except for 411) It’s accessible here and in Jira. The Maintenance Release will be officially launch on the 6th january week. By then, work and discussion can start on the ticket chosen for this MR.

CDI EG meeting 12/09/2013 notes on CDI 1.2 MR

Posted by Antoine Sabot-Durand on Dec 09, 2013 | Comments

The following people assisted this meeting :

  • Pete Muir (pm)

  • Jozef Hartinger (jh)

  • Martin Kouba (mk)

  • JJ Snyder (jj)

  • Antoine Sabot-Durand (asd)

Proposed Agenda

The following agenda was proposed

  1. Issues discussion : 6 issues where proposed

  2. Back on CDI-377 (automatic JSR-330 annotation processing problematic)

Issues discussion

The discussion around the proposed ticket was quite straight forward. The result is in the table below

Jira Description Decision Note

CDI-380

Clarify SessionScoped

in MR

We should be less descriptive and like for CDI-381 add a general statement telling that other spec/extensions can change the behavior of built-in scope

CDI-372

clarify behavior of implicit bean archive

in MR

The notion of Bean Archive is introduce in Chapter 12, we should do an introduction before

CDI-320

Clarify whether ProcessAnnotatedType should be fired for annotations

in MR

According to pm it shouldn’t and we should clarify this

CDI-318

@WithAnnotations types can appear on any supertype

in MR

Mainly Javadoc correction on @WithAnnotation

CDI-280

behavior of CDI bean @Specializes session bean is undefined

in MR

could benefit some clarification

CDI-220

Clarify interceptors are not associated with the result of a producer method/field

in MR

Back on CDI-377 (automatic JSR-330 annotation processing problematic)

This issue will be fixed in implementation and the sepc will mention something about recommendation to provide default exclusion list for most framework. We still have to discuss if we introduce a jar exclusion mechanism in the spec or this will be based on existing package exclusion.

Conclusion

We finished to deal with the list of Jira tickets we planned to introduce or not in MR. As we have a little more time it was decided to re-open the list for some more on next meeting

CDI EG meeting 12/02/2013 notes on CDI 1.2 MR

Posted by Antoine Sabot-Durand on Dec 02, 2013 | Comments

The following people assisted this meeting :

  • Pete Muir (pm)

  • Mark Struberg (ms)

  • Jozef Hartinger (jh)

  • Joseph Bergmark (jb)

  • Phil Zampino (pz) (Java EE EG member)

  • JJ Snyder (jj)

  • Antoine Sabot-Durand (asd)

Proposed Agenda

The following agenda was proposed

  1. Feed back on Java EE EG conf call we had on tuesday

  2. Issues discussion : 9 issues where proposed

Feedback on Java EE EG meeting

To sum up :

  • Java EE EG is ok with our MR roadmap :

    • 16th Dec - list of issues complete

    • 6th Jan - Maintenance review starts

    • 7th March - Maintenance review ends

    • 21st March - Maintenance ballot ends

  • According to JCP rules on update, we are going for CDI 1.2 (not 1.1.1)

  • Regarding ticket CDI-370 (Expand @RequestScoped and @SessionScoped to account for WebSocket) we agree that job should be done in Websocket Spec. So asd will work with Stuart Douglas to bring this point to the Websocket EG. The direct consequence for our MR is that CDI-370 is not in and should be closed after we check that Websocket EG got the point on their side.

  • We also talk about classloader issue that were raised during CDI-377 (automatic JSR-330 annotation processing problematic). EG members agreed that it’s a good point but very difficult to resolve. It could only be solve in a major EE release.

Issues discussion

The discussion around the proposed ticket was quite straight forward. The result is in the table below

Jira Description Decision Note

CDI-405

Reword the description of @RequestScoped and @ApplicationScoped in section 2.4.1

in MR

CDI-401

Clarify the meaning of "bean class local view"

in MR

CDI-398

Clarify that an array with a variable component type or parameterized component type containing wildcards is not a valid bean type

in MR

CDI-392

Clarify when the operations of BeanManager can be called

in MR

CDI-386

Two examples in section 5.2.4 contradict the rules of the same section

in MR

CDI-382

Clarify interceptors are not associated with the result of a producer method/field

in MR

CDI-381

Additional implementations of Request Context

in MR

we should add general statement telling that extension can change the behavior of built-in scope

CDI-379

Clarify life cycle of RequestScoped

out MR

each spec should detail how they stick to built-in scope

CDI-77

Clarify what happens when the user creates a unbound recursive injection with Dependent scoped beans

out MR

Container doesn’t have to support this : the ticket should be closed

Conclusion

EG has still 8 issues to discuss (inluding CDI-377). We should close the list as planned on mid-december.