Java Reference
In-Depth Information
FactoryBean is an interface
implemented by beans to provide it with a chance to customize the
creation of another type of object, above and beyond what the container knows how to do.
FactoryBean
is
also generic-friendly. This is rarely something you'll deal with unless you write a custom
FactoryBean
or
decide to inject another
FactoryBean
and manipulate it manually. The new interface looks like this:
public interface FactoryBean<T> {
T getObject() throws Exception;
Class<? extends T> getObjectType();
boolean isSingleton();
}
ApplicationContext Events
ApplicationContext
events let you bring another level of decoupling to your application, going one step
farther than dependency injection. Beans declared in the application context can publish and subscribe
to events published by other beans. You might use this as a sort of publish/subscribe infrastructure
inside the virtual machine. It's a quick way to broadcast an event that other beans can subscribe to if
they want to. If a bean implements the
ApplicationListener
interface, it receives every
ApplicationEvent
that is published. However, this quickly becomes burdensome after a few different components start
publishing an
ApplicationEvent
, if only because of the requirement to filter incoming events with
instanceof
checks.
Now you can stipulate what type of
ApplicationEvent
your bean will receive by using a type
parameter. To broadcast an event, your event must still subclass
ApplicationEvent
. In the following
example, the
ApplicationContext
is used to publish a subclass of
ApplicationEvent
called
CopiesExhaustedApplicationEvent
, which is published only when the library has exhausted the
available copies of a given topic:
public class LibraryServiceImpl
implements LibraryService, ApplicationContextAware, InitializingBean {
private List<Book> books;
private ApplicationContext context;
// …
public boolean checkOutBook(Book topic) {
if (this.books.contains(book)) {
if (book.getTotalCopiesAvailable() > 0) {
book.setTotalCopiesAvailable(
book.getTotalCopiesAvailable() - 1);
return true;
} else {
ApplicationEvent evt = new CopiesExhaustedApplicationEvent(
this, book);
context.publishEvent(evt);
return false;
}
}
return false;
}
Search WWH ::
Custom Search