I saw InjectionPoint mentioned breifly by Adam Bien in his JavaOne 2011 Presentation JavaEE 6 Cool Parts (around about 0:50).

There wasn’t much information about it though I found the Javadoc at http://docs.oracle.com/javaee/6/api/javax/enterprise/inject/spi/InjectionPoint.html and it had all I needed to know.

For example, the following producer method creates injectable Loggers. The log category of a Logger depends upon the class of the object into which it is injected.

@Produces
Logger createLogger(InjectionPoint injectionPoint) {
return Logger.getLogger( injectionPoint.getMember().getDeclaringClass().getName() );
}

And it works!

//index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html">
  <h:head>
    <title>Facelet Title
  </h:head>
  <h:body>
    Hello from Facelets
    <h:form>
      <h:commandButton value="Injector seat!" action="#{messenger.hello}"/>
    </h:form>
  </h:body>
</html>
// Messenger.java
package boundary;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.inject.Named;

/**
 *
 * @author bsmith
 */
@Named
public class Messenger {
    @Inject String data;
    @Inject Logger log;

    public void hello() {
        System.out.println("Hello!  I want: "+data);
        log.log(Level.SEVERE, "("+log.getName()+") I am logging some data: "+data);
    }
}
// Configuration.java
package control;

import java.util.logging.Logger;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

/**
 *
 * @author bsmith
 */
public class Configuration {
    @Produces
    public String getData(InjectionPoint ip) {
        System.out.println("ip.toString: "+ip.toString());
        System.out.println("ip.getAnnotated: "+ip.getAnnotated());
        System.out.println("ip.getBean: "+ip.getBean());
        return "data";
    }

    @Produces
    public Logger getLogger(InjectionPoint ip) {
        return Logger.getLogger( ip.getMember().getDeclaringClass().getName() );
    }
}

INFO: com.tintuna_Injection_war_1.0-SNAPSHOT was successfully deployed in 398 milliseconds.
INFO: ip.toString: [field] @Inject boundary.Messenger.data
INFO: ip.getAnnotated: [field] @Inject boundary.Messenger.data
INFO: ip.getBean: Managed Bean [class boundary.Messenger] with qualifiers [@Any @Default @Named]
INFO: Hello!  I want: data
SEVERE: (boundary.Messenger) I am logging some data: data
Written on October 13th, 2012 , EJB, Java Tags: , ,

Comments are closed.

Brooke Smith is proudly powered by WordPress and the Theme Adventure by Eric Schwarz
Entries (RSS) and Comments (RSS).

Brooke Smith

Portfolio and site of a software engineer