adam bien's blog

How To Replace Classes With Java EE--After The Fact 📎

With Java EE you can replace all injected classes without using an interface, factory or any other creational pattern.

The class Greeter:


public class Greeter {

    public String getGreetings(){
        return "Hey duke";
    }
}


...is directly injected into the Index:


import javax.enterprise.inject.Model;
import javax.inject.Inject;

public class Index {
    
    @Inject
    Greeter greeter;
    
    
    public String getMessage() {
        return content;
    }

}


PoliteGreeter replaces the Greeter using inheritance and applying the annotation @Specializes


import javax.enterprise.inject.Specializes;

@Specializes
public class PoliteGreeter extends Greeter{

    @Override
    public String getGreetings() {
        return "Dear " + super.getGreetings();
    }
}


The @Specializes mechanism is used to provide custom behavior / configuration for the porcupine and breakr utils. This post is motivated by the following porcupine issue.

Any questions left? See you at Java EE Workshops at Munich Airport, Terminal 2 and particularly at Bootstrap Java EE 7 or airhacks.io.

[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 235 in, chapter "Plugins"]. Sample is based on the template flavor of the plugin pattern.