DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Introducing SmallRye LLM: Injecting Langchain4J AI Services
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • Extending the Power of Jakarta EE and MicroProfile With CDI Extension
  • Archiving Composition Over the Heritage With CDI Decorator and Delegator

Trending

  • Measuring the Impact of AI on Software Engineering Productivity
  • AI’s Role in Everyday Development
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. CDI-JSF: Using the CDI @Observes

CDI-JSF: Using the CDI @Observes

See the CDI @Observes annotation in action for your JSF projects — in this case, setting up fire alarms for various neighborhoods.

By 
Anghel Leonard user avatar
Anghel Leonard
DZone Core CORE ·
Nov. 14, 16 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
13.7K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will discuss using the CDI @Observes in a JSF application.

Basically, we will exploit the fact that Java EE provides an easier implementation of the observer design pattern via the @Observes annotation and javax.enterprise.event.Event<T> interface.

Note In the bellow examples, we will use CDI managed beans, but you can use EJB 3 beans also. Basically, the observer pattern is based on a subject and some observers:

  • Subject: an object that changes its state.

  • Observers: objects notified when the subject has changed its state.

This time, the subject is a CDI managed bean named, MainFireStationBean:

@Named
@RequestScoped
public class MainFireStationBean {

    @Inject
    Event<String> evt;

    public void fireStarted(String address) {
        evt.fire(address);
    }
}


The container injects an Event object of type String into the evt instance variable of the   MainFireStationBean class (practically, this String represents the fire address). To activate an event, call the javax.enterprise.event.Event.fire() method. This method fires an event and notifies any observer methods (observers). Now the observable part is completed, so it is time to create the observers that listens for our String events.

In Java EE, the observers are marked with the @Observes annotation. The addition of the @Observes annotation to the method signature instructs the container that this method should act as an observer of events of the type it precedes. 

We have three observers, ViningsFireStationBean, BrookhavenFireStationBean, and   DecaturFireStationBean:

@Named
@Dependent
public class ViningsFireStationBean {

    public void update(@Observes String arg) {
         System.out.println("Vinings fire department will go to " + arg);
    }
}

@Named
@Dependent
public class BrookhavenFireStationBean {

    public void update(@Observes String arg) {
        System.out.println("Brookhaven fire department will go to " + arg);
    }
}

@Named
@Dependent
public class DecaturFireStationBean {

    public void update(@Observes String arg) {
        System.out.println("Decatur fire department will go to " + arg);
    }
}


So, the @Observes annotation precedes the type String and thus listens for events of that type. The @Observes annotation followed by an object type instruct the container with all the needed information.

In order to test it, we just need to report some fires. We can do this in several ways, but let's do it quickly via two JSF buttons:
<h:form>
    <h:commandButton value="Report Fire at Home Park Atlanta" 
                     action="#{mainFireStationBean.fireStarted('Home Park Atlanta, GA')}"/>
    <h:commandButton value="Report Fire at High Museum of Art" 
                     action="#{mainFireStationBean.fireStarted('High Museum of Art 1280 Peachtree St NE Atlanta, GA 30309')}"/>
</h:form>


If we suppose that the Report Fire at Home Park Atlanta button was pressed then the output will be:

Decatur fire department will go to Home Park Atlanta, GA

Vinings fire department will go to Home Park Atlanta, GA

Brookhaven fire department will go to Home Park Atlanta, GA


So, everything works as expected. The complete example is available here.

One step further and we will want to differentiate between the same object types of objects and set up different observers to listen for them. For example, we may need to distinguish between small fires and big fires. Depending on this aspect, a local fire station may send to the fire address one fire truck or multiple fire trucks. We can model this case via a qualifier:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface FireType {

    Type value();

    enum Type {
        SMALL, BIG
    }
}


The two enum types (SMALL and BIG) will be used to act as annotation to mark the strings to be fired by the event instances. So, the MainFireStationBean will be:
@Named
@RequestScoped
public class MainFireStationBean {

    @Inject
    @FireType(Type.SMALL)
    Event<String> small;

    @Inject
    @FireType(Type.BIG)
    Event<String> big;

    public void fireStarted(String address, boolean t) {
        if (t) {
            small.fire(address);
        } else {
            big.fire(address);
        }
    }
}


Finally, add the annotations to the observer part:
@Named
@Dependent
public class ViningsFireStationBean {

    public void updateSmallFire(@Observes @FireType(FireType.Type.SMALL) String arg) {
        System.out.println("Vinings fire department will go to a small fire at " + arg);
    }

    public void updateBigFire(@Observes @FireType(FireType.Type.BIG) String arg) {
        System.out.println("Vinings fire department will go to a big fire at " + arg);
    }
}

@Named
@Dependent
public class BrookhavenFireStationBean {

    public void updateSmallFire(@Observes @FireType(FireType.Type.SMALL) String arg) {
        System.out.println("Brookhaven fire department will go to a small fire at " + arg);
    }

    public void updateBigFire(@Observes @FireType(FireType.Type.BIG) String arg) {
         System.out.println("Brookhaven fire department will go to a big fire at " + arg);
    }
}

@Named
@Dependent
public class DecaturFireStationBean {

    public void updateSmallFire(@Observes @FireType(FireType.Type.SMALL) String arg) {
        System.out.println("Decatur fire department will go to a small fire at " + arg);
    }

    public void updateBigFire(@Observes @FireType(FireType.Type.BIG) String arg) {
        System.out.println("Decatur fire department will go to a big fire at " + arg);
    }
}



Now, let's report a big fire and a small fire:
<h:form>
    <h:commandButton value="Report a Small Fire at Home Park Atlanta" 
                     action="#{mainFireStationBean.fireStarted('Home Park Atlanta, GA', true)}"/>
    <h:commandButton value="Report a Big Fire at High Museum of Art" 
                     action="#{mainFireStationBean.fireStarted('High Museum of Art 1280 Peachtree St NE Atlanta, GA 30309', false)}"/>
</h:form>  


In case of a small fire, the output will be:

Brookhaven fire department will go to a small fire at Home Park Atlanta, GA

Vinings fire department will go to a small fire at Home Park Atlanta, GA

Decatur fire department will go to a small fire at Home Park Atlanta, GA


Note that in case of your own object types, you don't need qualifiers. Since the object type is unique, you can fire/observe your own object types by using the object.

The complete example is available here.

CDI

Published at DZone with permission of Anghel Leonard, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Introducing SmallRye LLM: Injecting Langchain4J AI Services
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • Extending the Power of Jakarta EE and MicroProfile With CDI Extension
  • Archiving Composition Over the Heritage With CDI Decorator and Delegator

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: