Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I add support for PropertyChangeSupport and PropertyChangeListener in a Java bean for a web application?

I noticed that some people write beans with support for the Property Change observer pattern.

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;

public class SampleBean implements Serializable {
    public static final String PROP_SAMPLE_PROPERTY = "sampleProperty";
    private String sampleProperty;
    private PropertyChangeSupport propertySupport;

    public ChartBean() {
        propertySupport = new PropertyChangeSupport(this);
    }

    public String getSampleProperty() {
        return sampleProperty;
    }

    public void setSampleProperty(String value) {
        String oldValue = sampleProperty;
        sampleProperty = value;
        propertySupport.firePropertyChange(PROP_SAMPLE_PROPERTY, oldValue, sampleProperty);
    }


    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertySupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertySupport.removePropertyChangeListener(listener);
    }
}

However, I remember reading that observer pattern is not commonly used in web based MVC patterns, due to the stateless nature of web applications.

Is it a good practice to follow the above pattern in web application Java beans?

like image 699
James McMahon Avatar asked Jun 09 '09 19:06

James McMahon


People also ask

What is Propertychangesupport Java?

It manages a list of listeners and dispatches PropertyChangeEvent s to them. You can use an instance of this class as a member field of your bean and delegate these types of work to it. The PropertyChangeListener can be registered for all properties or for a property specified by name.

What is JavaBeans in advance Java?

JavaBeans is a portable, platform-independent model written in Java Programming Language. Its components are referred to as beans. In simple terms, JavaBeans are classes which encapsulate several objects into a single object. It helps in accessing these object from multiple places.


1 Answers

To be honest only bother if you are actually going to need the feature. Most web applications don't need PropertyChangeSupport. I can't actually remember seeing it being used in any web app that I've seen. I've only seen it being used a Swing application.

A typical bean in a web application is a pretty short lived object, prepared to service the single request and then cast off in to the void to be garbage collected. The main issue is that web applications are my there nature concurrent and multi user this doesn't lend it self to longer lived objects with listeners and events etc.

like image 131
Gareth Davis Avatar answered Oct 19 '22 09:10

Gareth Davis