Jul
31
2005
0

Replying to Floyd, Ted, Keith and Arjen

There’s a debate going on about Spring, the history of EJBs and distribution. Here’s a summary of what’s been going on the last week:

Replying to Arjen

Interestingly enough, I had a fair bit of discussion with my colleague Arjen on the subject of web services and distribution lately. In his latest post, Arjen tries to interpret my latest post about exposing use cases. After I re-read the bit I wrote a couple of days ago I’m kind of amazed that he actually drew the right conclusion because I think the bit I wrote wasn’t the most clear entry ever…

Anyway, Arjen concludes by stating that he thinks it’s about making Web Services first class citizens of your application architecture.

He’s right, but I think it’s important to take one step back and first try to understand that a Java Interface in fact DOES NOT always have to be the same as your Web Service contract.

The point I was trying to get across in my previous post on exposing use cases was that some situations simply don’t lend themselves for transparently exposing a Java Interface as a web service.

Replying to Ted (and Floyd and Keith)

The whole discussion closely relates to the one currently going on between Ted, Keith and Floyd on the history of EJB. After Keith counters Ted by stating that ‘it is wrong to say Spring encourages a “distributed-objects-first” approach, or even the use of distribution in the first place’. Ted agrees but in a way he doesn’t seem to like Spring’s approach. Not because it’s intrinsically wrong but because too often he runs ‘into developers who are of the “objects uber alles” mindset, and any technology that allows them to go back to their basic O-O principles is obviously a Good Thing’. He goes on to state that he’s ‘more worried about the folks who pick up Spring second-hand and use it after reading a few tidbits about POJOs and such. THEY’re the ones who’re going to give Spring the bad name… because in many respects they’re the same ones who did it to EJB’.

Reading between the lines you could conclude that Ted thinks that the majority of developers by nature is not smart enough to understand distributed architectures, web services and such and that’s it’s best to create explicit hard-to-work-with concepts to make those developers realize that they’re dealing with distribution and remote objects (err… services).

I partly agree. I also encounter developers that don’t understand distribution and the issues that come with it. But in practice it takes me only an hour or so to explain these issues and make them realize that they should be careful when distributing objects or working with web services. Explaining network latency and interoperability issues isn’t that hard Ted!

I guess it comes to what’s you’re really after. I think we should be after:

creating the right conditions for a model in which distribution is easy and that clearly recognizes the importance of dealing with latency and interop while at the same time promoting web and distribution services as a separate first-class citizens of the application architecture

Remember: this doesn’t mean we’re there yet!!. As Keith noted: ‘the Spring container itself does not address the problem of distributing objects at all, period’. Keith is explicitly talking about the container, because that’s what’s at the heart of Spring and focusses on in-process development, not inter-process development. My guess is we really need to get the in-process development stuff right first and in the meantime think about technologies on top of that model that facilitate the development of distributed services (whether it be RPC-style services or document-oriented web services).

In other words: I don’t like being pessimistic about what developers are capable of and preventing them from doing the wrong things by lots of tooling and complex things they have to go through. It’s a bit like solving the problems in third-world countries by just throwing money and food at them while a better approach might be to actually learn them how to grow there own grain.

To be continued I guess…

Written by Alef in: Java-related, Spring |
Jul
27
2005
3

How to expose use cases to users – web services, remoting & GUIs

How to expose use cases to users – web services, remoting & GUIs

In light of recent discussions I had with Arjen Poutsma about service oriented architectures and the development of web services I’d like to talk a bit about how to expose use cases to users. Users in this case in the broadest sense; meaning not only people, but also other systems.

Most of the material in this article is the result of discussions I had with Arjen Poutsma. On his blog, you can read more about his thoughts on web services and why web services are NOT the same as remote procedure calls.

Use cases

Application development is about implementing functionality of some sort. An application that enables the user to transfer money from one bank account to another usually contains some functionality that checks for the current balance of a bank account and iff enough money is available, transfers the money to the other account. The transferring of money to an account is what we call a use case.

We all know that layering is a Good Thing to do when implementing applications containing lots use cases involving complex business logic. Some argue here, but in the case of Kevin certainly for the wrong reasons. It’s clear that the reasons he gives for not layering your application design are completely overruled by the rise of ligthweight frameworks such as Spring. But let’s not argue too much with the purpose of ligthweight application frameworks here, afterall, the title of the post is ‘How to expose use cases to users’, it doesn’t state ‘the purpose of lightweight frameworks’!

Back to use cses. Most business applications consist of use cases modelled using one or more service interfaces. The following is a typical service interface:

public interface Teller {
 
  void transferMoney(BankAccount from, BankAccount to, double amount)
  throws InsufficientBalanceException;
}

The service interface defines what our application is capable of, it provides the user with a clearly defined collection of individual pieces of functionality. It doesn’t state how those pieces of functionality are implemented and as user of the application, you probably shouldn’t care less. One thing you do care about as a user is the ability to actually use the functionality the interface (the interfaces) defines.

A user interface – a way to access functionality

To cut things a bit short, when talking about accessing functionality of an application, we can divide users into two distinct groups: users as in people and users as in other systems. This division isn’t necessarily needed for the rest of the article, but it’s serves well to talk a bit about user interfaces.

A user interface is needed for users to interface with the functionality an application provides. The first group of users (the actual people) will most often access the functionality provided using a Graphical User Interface (GUI) and nowadays this often is a web interface. The second group of users will probably resort to using a different kind of interface. Some systems still have to screen scrape a mainframe terminal which you could call a graphical user interface as well, but oh well, fortunately I don’t have to deal with that too much so let’s forget about that.

Different users, different systems

Some people are (color-)blind, some are not, some are deaf, some are not. In short, there are different groups of people we have to deal with when implementing a Graphical User Interface. When implementing an interface for a system to access functionality provided by an application there are probably even more distinct groups we have to deal with. Some system users (as we’ll call ‘em throughout the article) might be implemented using Perl or Ruby, some might only know of a certain platform called .NET they live on. While others are fast as the latest Ferrari and demand a fast response, some might be really really slow. Last but probably not least, there might be system users that live in a single address space while others are distributed across several nodes on the other side of the globe.

To conclude my bit about different system users, I’d like to quote Waldo et. al:

Objects that interact in a distributed system need to be dealt
with in ways that are intrinsically different from objects that
interact in a single address space.

Inter-process communication

When two distinct processes positioned in one single address space implemented in the same language have to talk to eachother people often resort to something like RMI, CORBA, DCOM or some maybe a somewhat less common protocol such as Hessian. This kind of inter process communication is based on a lot of assumptions. When one of those assumption is dropped, things become a lot more complicated. When for example the two different applications that need communicate are implemented in different language, all of a sudden we have to deal with different type mechanisms. When the two systems are not in the same network segment firewall issues might arise or problems with network latency.

Re-reading the Waldo’s statement might help here :) .

Concluding all this, we can say that designing ways to access use cases with a distributed topology in mind greatly increases complexity and introduces all kinds of aspects we don’t have to deal with when invoking functionality positioned in the same process.

Introducing web services

Web services are positioned as a way to solve some of the problems we introduced in the last paragraph. Wikipedia defines web services as follows:

A Web service is a collection of protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards. OASIS and the W3c are the steering committees responsible for the architecture and standardization of web services. To improve interoperability between web service implementations, the WS-I organisation has been developing a series of profiles to further define the standards involved.

When I started to use web services, I ended up exposing my service interface as a web service. Using something like Axis this is fairly easy. Until you run into somewhat more complex situations, transparently exposing your service interface is all you might need. But while at it, you quickly start to ignore the problems we’ve just reviewed; interoperability, network latency, et cetera. You might even start to think of web services as just another way to implement Remote Procedure Calls (RPC). This conclusion can in fact be quite dangerous because of all those latency and interoperabilitty issues.

Back to user interfaces

When reviewing what we’ve said about Graphical User Interfaces a surprising amount of aspects that come with developing GUIs also holds for developing user interfaces for system users. We have to deal with different types of users (systems) and so on. Furthermore we also have to deal with different types of functionality. Some applications are CRUD-only (for which we can easily develop a generic solution such as Ruby on Rails’ ActiveRecord or the Spring equivalent. Some are more complex and require more sophisticated form handling. Somehow we still haven’t been able to come up with one perfect solution that suits all our needs and removes the burden of custom coding alltogether. And to be honest, I think we’ll never get there! To some extend, a certain amount of programming will always be required when creating Graphical User Interfaces.

I’d like to conclude with the remark that in my opinion the same holds for other user interfaces. When creating web services, the simplest approach possible is transparently exposing your service interface and letting the stack generate (dynamically or at build time) all the necessary type conversions, protocol endpoints, etcetera. For Java-to-Java communication RMI or Hessian for example perfectly do the job here. However, the more complex your requirements are getting, the more coding you’ll have to do. You’ll probably end up using a web services stack with all its added complexity. When dealing with complex schemas for example, you might want complete control over the way your web service implementation is going to convert the XML to Java objects. You might want control over the SOAP headers that were passed as part of the SOAP request. Sometimes contract-first development is the best thing to do, sometimes you just want your web service description to be generated based on the service interface.

Arjen addresses all of those issues in the blog entries listed below. In my opinion, a web services stack should just as an MVC framework support both the simplest approach possible as well as the most complex approach you can think of. In other words: simple things should be made even simpler but complex things should always be possible!

More to come…

Excellent blog entries by Arjen on issues with web services:


Written by Alef in: Java-related, Other, Spring |
Jul
20
2005
2

Alev Arends?

Last May, Rod Johnson and me were interviewed about Spring at one of the bi-annual NL-jug meetings. We were interviewed by Mr. Dre de Man of the Dutch Java Magazine.

The result of the interview has been published in one of the printed editions of the Java Magazine. Unfortunately Mr. de Man misspelled my name. Instead of Alef Arendsen he subtitled the article “Gesprek met Rod Johnson en Alev Arends“.

This is a bit of an experiment to see if I can get my site up on Google when people search for “Alev Arends”. Let’s see if it works!

Update: well, Google did it again! When querying Google for “Alev Arends”, this site pops up as the first result!

Written by Alef in: Other |
Jul
14
2005
1

Theme changes

I’ve changed my theme around a two times the last couple of weeks. The current is likely to stay around for quite some time. I’ve looked for an appropriate one that makes it easy to read things. A fixed-width-column style blog doesn’t really fit that well since the code snippets are quite likely to become too big and the article too lengthy.

This theme by the way is called Giraffe and I got it after Colin Sampaleanu installed it on the Interface21 blog site.

Written by Alef in: Other |
Jul
13
2005
7

Spring instance management part II – hotswapping (!) and mixins for pooling

In the previous post I elaborated on the way Spring supports pooling. In this article I’d like to cover some performance characteristics, the ability to provide insight in the statistics of the pool we’ve previously configured and the way we can use the TargetSource we discussed previously to implement hotswapping.

Performance overhead

Okay, let’s get this out of the way. When you start introducing AOP in your application (be it Spring AOP, AspectJ, JBoss AOP or whatever other AOP library), you are likely to run into a performance hit! There’s no way around it. Somehow the AOP framework needs to be able to add the additional behavior (advices) to the program flow. Spring is using proxies to do the trick. I don’t want to spend too much time on this, so let’s get down to the numbers immediately. I’ve implemented a small test that simulates the following situations:

  1. PortalManager in combination with a new DocumentParser per request
  2. PortalManager in combination with a pooled DocumentParser

Scenario 1) on an iMac G5 uses approximately 200 milliseconds for 1 mln calls. The second scenario (so with pooling added that is) takes somewhat over 10 times as long (2100 milliseconds to be precise).

So to conclude: yes, pooling adds overhead (although the overhead is probably for 50% caused by the AOP framework)! That’s why in the previous post I already stressed that pooling should be applied carefully! For helpers that take a really long time to instantiate it can provide help; for simple helpers however you should probably just wire them as prototypes and go with that. If you really need pooling (and this also holds for a lot of the other coarse-grained AOP functionality Spring provides) you shouldn’t care too much about the small overhead since it removes a lot of code-tangling and has all the other benefits AOP offers you (and which I won’t start a discussion about that here) and secondly, the operations involved might even deal with databases, JMS, XML parsing which take way longer than the overhead of AOP anyway.

Mixins to provide insight into the pooling statistics

Okay, there you have it :) , AOP adds overhead. Let’s get down to something more interesting: the ability to get insight into the pooling statistics. For management purposes it might be good to get some detail on how many objects are in the pool. The Commons Pool has these statistics available for your, but since we’re transparently introducing pooling behavior, we’re not really able to get to the information without some dirty hacks. That’s why we’re going to introduce the statistics information to our pooled class! We’re going to do this using a mixin. This is hopefully the last time I’m using this awful buzzword in this post. From now on I’ll talk about the ‘introduction of new behavior’.

Spring features the org.springframework.aop.target.PoolingConfig interface which has methods like getActiveCount(), getIdleCount() and getMaxSize(). After we’re done with the magic which is coming in a minute, we’ll be able to do the following with our pooled DocumentParser:

class ParserMonitor {
 
  private PoolingConfig poolingConfig;
  
  void setPoolingConfig(PoolingConfig poolingConfig) {
    this.poolingConfig = poolingConfig;
  }
}
 
<bean id="documentParserTarget" 
  class="example.DocumentParser"/>
 
<bean id="documentParser"
  class="org.sprfr.aop.framework.ProxyFactoryBean">
  <property name="targetSource">
    <bean class="org.sprfr.aop.target.CommonsPoolTargetSource">
      <property name="targetBeanName"
        value="documentParserTarget"/>
    </bean>
  </property>
  <!-- some additional stuff -->
</bean>
 
<bean id="monitor" class="example.ParserMonitor">
  <property name="poolingConfig" ref="documentParser"/>
</bean>

The documentParser bean definition is the same as the definition from the last post..

But hey! This means that somehow, the DocumentParser now also implements the PoolingConfig interface. If you look closely, the document parser is passed to the setPoolingConfig() method that takes a PoolingConfig, not a DocumentParser.

Wiring the introduction

The above is what we call an introduction of extra behavior. Through the use of AOP, we’re able to let a class implement an extra interface in a dynamic way. This means, at compile time, the class does not implement this interface but at runtime (when it’s configured using a ProxyFactoryBean) it does!

The configuration is pretty simple. First we wire the target source:

<bean id="poolingTargetSource" 
  class="org.sprfr.aop.target.CommonsPoolTargetSource">
  <property name="targetBeanName" value="documentParserTarget"/>
</bean>

The target source has a getter for the advisor that produced the introduction. It’s a bit too much to go into this in detail, so let’s just assume we need it:

<bean id="poolingConfigMixin" 
  class="org.sprfr.beans.factory.config.MethodInvokingFactoryBean">
  <property name="targetObject" ref="target"/>
  <property name="targetMethod" value="getPoolingConfigMixin"/>
</bean>

The last thing we need to do is wire the proxy factory bean. This resembles the way we did it in the first part of the series of posts on instance management. This however includes the poolingConfigMixin bean as part of the interceptors.

<bean id="documentParser" 
  class="org.sprfr.aop.framework.ProxyFactoryBean">
  <property name="targetSource" ref="target"/>
  <property name="proxyInterfaces" 
    value="com.interface21.pooling.DocumentParser"/>
  <property name="interceptorNames" value="poolingConfigMixin"/>
</bean>

After we’ve added this to our context, we’ll be able to let the ParserMonitor from the snippet above inspect the statistics of our pool. Using Spring’s JMX features we can also for example expose the monitor to a JMX MBeanServer to inspect it using JMX. Pretty cool stuff all without changing a single line of code in our application. This functionality is by the way all provided by AOP. If you’re interested in the concepts behind all of this, you should definitely read some more about AOP, advisors and introductions.

Caution!

As mentioned all over the place in the reference manual as well, you should not just go and pool all the objects in your context just for fun. It DOES provide overhead

Hot-swapping your beans

So let’s see if the target sources can provide us with some other nice functionality. Suppose (in the portal we’ve previously discussed) we actually have two backends, one that takes all the requests and the other one that acts as a fallback in case the first one somehow falls over.

Let’s consider the portal manager:

class PortalManager {
  void setDocumentParser(DocumentParser parser) {
    this.parser = parser;
  }
  void setPortalBackend(PortalBackend backend) { 
    this.backend = backend;
  }
 
  PortalDocument getPortalDocument(String query) {
    InputStream is = backend.query(query);
    return parser.parse(is);
  }
}

We’ve seen the DocumentParser before, but this time we’re more interested in the PortalBackend which is communicating with the backend that provides the results for a specific query. Let’s first wire the two backends:

<bean id="primaryBackend" class="example.PortalBackendImpl">
  <property name="url" value="http://10.0.0.2/path"/>
</bean>
 
<bean id="secondaryBackend" class="example.PortalBackendImpl">
  <property name="url" value="http://10.0.0.3/path"/>
</bean>

Using the ‘normal’ DI way of configuring things, we can only wire one backend to the PortalManager. Using a target source, we’ll now create a small indirection that helps us switch to the second backend if the first one falls over.

<bean id="swappingBackendTargetSource"
  class="org.sprfr.aop.target.HotSwappableTargetSource">
  <constructor -arg ref="primaryBackend"/>
</bean>

Using constructor injection, we’re specifying the initial target. Now, we wire the ProxyFactoryBean with the newly created target source, just as we did with the poolingg target source:

<bean id="portalBackend"
  class="org.sprfr.aop.framework.ProxyFactoryBean">
  <property name="targetSource" ref="swappingBackendTargetSource"/>
</bean>

and we inject the proxy (which is going to retrieve the PortalBackend from the target source for us) into the PortalManager:

<bean class="example.PortalManager">
  <property name="portalBackend" ref="portalBackend"/>
</bean>

So the portal manager is done. Swapping the primary backend out and let the secondary backend pick up all the requests is pretty easy. The target source (with which we’ve configured the target using constructor injection) features a method to change the target called swap(). If we have a handle to the application context, we could easily do the following:

ApplicationContext ctx;
HotSwappableTargetSource hsts = 
  (HotSwappableTargetSource)ctx.getBean(
  "swappingBackendTargetSource");
 
Object secondaryBackend = 
  ctx.getBean("secondaryBackend");
hsts.swap(secondaryBackend);

All calls from now on are redirected to the new target we’ve specified (using the swap() method). You don’t have to worrry about threading, all the stuff necessary to swap out the old object for the new one are synchronized.

Now for the falling over of the first backend. We wouldn’t want to program this into our PortalManager. Let’s assume the PortalBackend throws a ConnectException when it somehow has gone out of order. Using a ThrowsAdvice, we’ll transparently swap out the old backend and replace it with the new one:

class BackendNotAvailableThrowsAdvice 
implements ThrowsAdvice {
 
  boolean primaryUsed = true;
 
  // other fields ommitted
  
  public void setPrimaryBackend(PortalBackend primary) {
    this.primary = primary;
  }

  public void setSecondaryBackend(PortalBackend secondary) {
    this.secondary = secondary;
  }
 
  public void setSwappingBackendTargetSource(
    HotSwappableTargetSource) {
    this.targetSource = targetSource;
  }
 
  void afterThrowing(Throwable exception) {
    if (exception instanceof ConnectException) {
      Object newTarget = primaryUsed ? secondary : primary;
      targetSource.swap(newTarget);
    }
  }
}

After we’ve wired up the advice, we’ll still get a ConnectException after the backend falls over (we can’t swallow exceptions in a ThrowsAdvice), but the next call will be redirected to the new backend and hopefully succeed.

<bean id="portalBackend"
  class="org.sprfr.aop.framework.ProxyFactoryBean">
  <property name="targetSource" ref="swappingBackendTargetSource"/>
  <property name="interceptorNames" value="backendThrowsAdvice"/>
</bean>
 
<bean id="backendThrowsAdvice singleton="true"
  class="example.BackendNotAvailableAdvice"
  autowire="byName"/>

Note: 1) the advice is a singleton since we’re keeping state in it and 2) we’re using autowiring here (by name, so the beans that are named according to the corresponding method will have to be available in the context

Again, this is not the most sophisticated construction out there since we’ll still get a connect exception if one of the backends falls over. Using an ordinary MethodInterceptor we change this. If you’re interested, I can cover that in a later entry.

Conclusion

Well, we’ve seen that AOP and pooling adds overhead, but that’s no surprise (at least, not to me). You’ll have to remember when using Spring’s AOP functionality and stuff like pooling that it’s all meant to take away the burden to code that infrastructural tidbits yourself and to have it all tangle across the code that really matters: the code that actually implements the customer’s needs. Secondly, it’s important to note that loads of J2EE apps communicate with an external resource and this probably takes WAY more time than executing AOP and pooling stuff. So remember this: don’t go and implement a ThrowsAdvice to catch IllegalArgumentExceptions that occur through your application! You’re probably better off implementing some kind of top-level exception handler here (like the HandlerExceptionResolver< /a> for web applications) or using AspectJ.

We’ve also reviewed a way to get insight into the statistics of our pool. Mixins are pretty powerful but also a technique you shouldn’t apply all over the place. To read more about mixins and AOP in general I recommend Ramnivas Laddad’s book or the one by Adrian Colyer and others.

Then there’s hot swapping. Out-of-the-box Spring provides features like this, and I hope you gained some insight into some of the things you can do will all those features. You should however not be afraid to go and implement your own TargetSource, ThrowsAdvice or stuff like that. It’s not that hard, it just takes some creativity and a bit of knowledge about the API.

Next time I’ll shortly review the other target sources available.

Written by Alef in: Java-related, Spring |
Jul
12
2005
2

Sonos Digital Music System Rocks!!

I just bought myself a Sonos Digital Music System. I just moved into my new house and wanted to get the music thing right from the start. I searched for receivers or other things that would do the trick but didn’t really find anything. Until one of the shops I visited came up with the Sonos DMS. A month later the first ones were shipped to Europe and I immediately bought one (last weekend).

The package contains three things:

  1. One ZonePlayer,
  2. another ZonePlayer and
  3. a remote

It all has a bit of the Apple L&F and the resemblence doesn’t stop there. Setting it up is just as easy as getting a Mac up-and-running:

  1. Connect one ZonePlayer to your network (for now wired, but using a gateway, you can change this) and power it up
  2. Attach some speakers to it
  3. Power up the other ZonePlayer in a different room after having connected some speakers to it (note: no wired network needed anymore since another ZP is present already)
  4. Install a tiny bit of software on your Mac
  5. Using the mute and volume button of your ZonePlayers, add them to your ‘digital music network’
  6. Share some music folders on your hard-drive of your PC or Mac

So what’s this all about. Well, using the remote, from now on you’ll be able to connect to Internet radio stations, play music of virtually any type (stored on for example your Mac or PC or on a network-wired Ethernet hard-drive). The extra benefits you get:

  • Different (or the same) music in diffferent rooms (you can add up to 30 something ZonePlayers to your network all capable of playing different music, all controlled by the remote)
  • No mare hassling with leaving your computer on or having to go to your computer to select some songs
  • No receiver needed, just some speakers
  • Colour display on the remote, showing album art and track info (it also has playlists, browsing of music, etcetera)

It simply rocks!

p.s. Okay Sonos, I’ve said way too much good things about your product, you better start paying me ;-) .

Written by Alef in: Java-related |
Jul
09
2005
11

Spring XML: way simpler since 1.2

Many people ask about me Spring’s XML format and question its verbosity. In this post I’d like to elaborate on Spring’s XML structure in general, some enhancements we made in Spring 1.2 and a short preview on what we’ll be adding in Spring 1.3.

To XML or not to XML

As most of you might know, there’s a long-running debate on the purpose of XML. XML in the Java-world is generally seen as a language which shouldn’t be used for procedural programming. By some people, one of the better examples of this ‘bad practice’ is considered to be Jelly.

I personally agree that XML shouldn’t be used to do scripting. XML documents should contain data. The data can be related to a particular business domain, but it might just as well be technical data.

In Spring, XML is used to inject objects with objects they depend on. In other words, the XML is used to ‘assemble’ your application from a number of components or classes you or other people have developed. The XML represents the static assembly of your application, the object graph that makes your application. Using Spring’s Dependency Injection container with the XML format it offers, you completely decouple you application code from the assembly of the final application the code is supposed to function in. Other people (like Keith and Dhananjay Nene more recently on TSS) elaborate more on the concept of Dependency Injection. I want to focus on Spring’s XML format and the benefits it brings.

To conclude to discussion on XML, I think that XML is a perfect way to express the static assembly of your application; the configuration that is needed to get things going. Actual behavior related to the problem your application is solving shouldn’t be coded in XML. That’s what the application code is for.

Spring’s XML format

Spring was first released in March 2004. In the first version the XML in some places got a bit verbose. Overall, the format for defining properties was verbose as well (for a reason, which we’ll review later). More than 300.000 downloads, 2 major releases and 9 minor ones later there have numerous enhancements and additions to the Spring Framework. One of the key areas in which improvements have been made is the XML format. In the next section I’ll guide you through some of the enhancements that have been made in 1.2 in particular, but also in the earlier releases. And still we’re not finished. Spring 1.3 will include a major new feature that will allow for even more compact XML that you will be able to customize to your own specific needs if you want. I’ll shortly elaborate on this as well.

Before we go on, I’d like to stress that I (and I think the Spring team as a whole) think the decision to begin with a consistent and simple XML format has been a really good one. The XML format Spring started out with is still usable and without any exception it covers all you need. If we would have gone for an XML format more tailored at specific use cases of the Spring Framework, first of all, the framework wouldn’t have been so extensible and usable as it is right now. Also, you probably would have found yourself in situations where the XML doesn’t suit the requirements you’re having. Things probably wouldn’t have been that flexible. The XML format Spring currently features is tailored to Dependency Injection and nothing more. As I’ve said already, 1.3 will include enhancements that will go beyond just that and will focus on more that just expressing object-types, dependencies and other properties.

The following is a detailed piece on a couple of enhancements that were made to the XML format since 1.0. I’ll try to keep historic discussions to a minimum but focus on real-world use cases and best practices instead.

Defining properties and bean references

One of the major enhancements in 1.2 was the addition of a simpler format for defining properties. The good-old way of defining properties was the following:

<bean class="example.Person">
  <property name="firstName">
    <value>Alef</value>
  </property>
</bean>

In 1.2, things have changed. From now on, you don’t need to include the nested value-tag anymore. Instead you can use the value-attribute. This comes with a small limitation however. Attributes aren’t allowed to contain <![CDATA]>, so if you want to specify CDATA text as the value for a specific property, you still need to use the nested value-tag (of course the old format is still supported). Here’s an example of how this new feature makes your XML much more concise:

<bean class="example.Person">
  <property name="firstName" value="Alef"/>
</bean>

Bean references in Spring 1.0 and 1.1 had to be defined using the nested or format where the latter points to a bean definition defined in the same XML file (XML ID are used here so validation of the XML will fail of you haven’t defined the bean). In Spring 1.2, what we’ve done for properties, has also been applied to the definition of bean references. In short, this comes down the following:

<bean id="someGirl" class="example.Person"/>
 
<bean class="example.Person">
  <property name="spouse" ref="someGirl"/>
</bean>

instead of

<bean class="example.Person">
  <property name="spouse">
    <ref bean="someGirl"/>
  </property><property>
</property></bean>

Factory and lookup methods

Spring is one fancy factory, we all know that. Sometimes however, you might need to incorporate a good-old factory in your application context. For some reason, you might not be able to get that old-style configuration out of the way (you might for example not have control over the code). In Spring 1.0, one thing you could use was the MethodInvokingFactoryBean, a FactoryBean that retrieves an object by calling a static method on a class or an instance method on a bean defined elsewhere in the context. This resulted in a bunch of XML. In Spring 1.1, short-hand ways to get this behavior have been introduced:

class MyStaticSpoolerFactory {
  public Spooler getInstance()
}
class Spooler {
  public Monitor getMonitor();

Considering the above class, you can now use:

<bean id="mySpooler" 
  class="example.MyStaticFactory" 
  factory-method="getInstance"/>
 
<bean id="myMonitor"
  factory-bean="mySpooler"
  factory-method="getMonitor"/>
 
<!-- pass the spooler monitor to a screen outputting status -->
<bean class="example.MonitorScreen">
  <property name="monitor" ref="myMonitor"/>
</bean>

instead of

<bean id="mySpooler"
  class="org.sprfr.beans.factory.config.MethodInvokingFactoryBean">
  <property name="targetClass">
    <value>example.MyStaticFactory</value>
  </property>
  <property name="targetMethod">
    <value>getInstance</value>
  </property>
</bean>
 
<bean id="myMonitor"
  class="org.sprfr.beans.factory.config.MethodInvokingFactoryBean">
  <property name="targetObject">
    <ref local="mySpooler"/>
  </property>
  <property name="targetMethod">
    <value>getMonitor</value>
  </property>
</bean>
 
<bean class="example.MonitorScreen">
  <property name="monitor">
    <ref local="myMonitor"/>
  </property>
</bean>

More info by the way on factory methods can be found in one of my previous posts.

Defining collections

Spring has supported the use of collections since it was first released. There are a couple of interested things you might not now about defining collections:

<property name="myList">
  <list>
    <value>Alef</value>
  </list>
</property>

is in fact the same as:

<property name="myList" value="Alef"/>

Of course the same works for a java.util.Set.

Note that this only works for a single value. The PropertyEditor machinery doesn’t support delimiting multiple elements by commas or things like that.

Inner beans

A feature not really spoken about that much is the ability to define so-called inner beans. Not only do inner beans result in more consistent XML, it also allows you to ‘hide’ beans from the entire context.

<bean class="example.Person">
  <property mame="firstName" value="Alef"/>
  <property name="children">
    <list>
      <bean class="example.Person">
        <property name="firstName" value="Peggy"/>
      </bean>
      <bean class="example.Person">
        <property name="firstName" value="Ricky"/>
      </bean>
    </list>
  </property>
</bean>

is much concise as

<bean class="example.Person">
  <property name="firstName" value="Alef"/>
  <property name="children">
    <list>
      <ref local="peggy"/>
      <ref local="ricky"/>
    </list>
  </property>
</bean>
 
<bean id="peggy" class="example.Person">
  <property name="dateOfBirth" value="20040607"/>
  <property name="firstName" value="Peggy"/>
</bean>
 
<bean id="ricky" class="example.Person">
  <property name="dateOfBirth" value="20040607"/>
  <property name="firstName" value="Ricky"/>
</bean>

Also, in the last example, both Alef as well as Maggy and Ricky are ‘first-class citizens’ in the Spring context. context.getBean("ricky") will give you the ricky bean while this might not be what you really want.

Inner beans were already part of Spring 1.0, however since then support has greatly increased. In earlier version for example, life cycle support wasn’t as good as it is now. Inner beans right now enjoy the same power as full-fledged beans.

Bean hierachies (parent and abstract)

In the example above, we saw some repition in the sense that for each bean we had to specify that it was of type example.Person and we also had to specify the date of birth for both Peggy and Ricky (question: are they twins? ;-) ).

Using Spring’s parent feature, you can leave out common properties of beans by specifying a parent. Let’s have a look at the parent feature at work:

<bean id="peggy" class="example.Person">
  <property name="dateOfBirth" value="20040607"/>
  <property name="firstName" value="Peggy"/>
</bean>
 
<bean id="ricky" parent="peggy">
  <property name="firstName" value="Ricky"/>
</bean>

In the above example, the ricky bean inherits all its properties from the peggy bean. It overrides however, the firstName property. This results in two beans, both of type example.Person, each with the same date of birth, but with a different first name.

Parent beans allows you to change the class as well. So we could also change the example to the following:

<bean id="peggy" class="example.Girl">
  <property name="dateOfBirth" value="20040607"/>
  <property name="firstName" value="Peggy"/>
</bean>
 
<bean id="ricky" class="example.Boy">
  <property name="firstName" value="Ricky"/>
</bean>

If you’ve seen this, you might in fact ask whether or not it’s possible to define abstract beans also. Well, as a matter of fact, it is! Let’s change the sample around a bit again:

<bean id="alef" class="example.Person"/>
 
<bean id="oneOfTheTwins" abstract="true">
  <property name="parent" ref="alef"/>
  <property name="dateOfBirth" value="20040607"/>
</bean>
 
<bean id="ricky" parent="oneOfTheTwins" class="example.Boy">
  <property name="firstName" value="Ricky"/>
</bean>
 
<bean id="ricky" parent="oneOfTheTwins" class="example.Girl">
  <property name="firstName" value="Peggy"/>
</bean>

As you can see, it’s pretty much possible to elimate all repitition using parent/child beans and the abstract feature.

Note that abstract beans are not instantiated by the Spring Dependency Injection container, nor will they be returned if you ask for them programmatically (context.getBean("oneOfTheTwins") that is).

Autowiring

Another interesting feature that not many of you might have seen is Spring’s autowiring capability. Spring heavily relies on reflection to inject dependencies and properties (not that this doesn’t impact performance really, since the larger part of your beans will be instantiated when the context or application is starting up–after that, no reflection is needed anymore since the beans have already been configured). Using reflection, Spring can also detect and automatically satisfy those dependencies. I will give a simple example here. For more in-depth information you should definitely have a look at the Spring reference manual where autowiring is covered in much more detail.

class MyDependency {
}
 
class MyManager {
  public void setDependency(MyDependency dep) {
    // assign dep to field
  }
}

If we consider the above manager and dependency, we can wire them up as follows:

<bean class="example.MyManager">
  <property name="dependency" ref="myDependency"/>
</bean>
 
<bean id="myDependency" class="example.MyDependency"/>

Using autowiring however, we can leave our the property element from the first bean definition, leaving us with just two one-liners:

<bean class="example.MyManager" autowire="byType"/>
 
<bean id="myDependency" class="example.MyDependency"/>

Of course, the above example doesn’t really add much value, since it’s such a simple configuration. But in large projects, it might in fact come in quite handy.

Spring’s autowiring feature can be used in one of four modes:

  • By type: Spring will try to satisfy dependencies based on the type (Class) defined in the JavaBean setter. This is what we used in the above example
  • By name: using this mode, Spring will satisfy dependencies by bean name. If we would rename the myDependency bean in the above example to dependency it would work as well, since the JavaBean setter has the same ‘name’ as the name of the bean
  • By constructor: will result in autowiring of the bean’s constructor instead of JavaBeans setters
  • Automatic: automatic autowiring is also supported. Spring will try to find the way it can satisfy the largest amount of dependencies of a specific bean. This works somewhat automagically and I must admit that I’m not a big fan of this specific type of autowiring

Personally I don’t use autowiring that much since I a pretty fast typer and I’d like to get things right and leave it with that. Some people however tend to use autowiring while prototyping parts of an application. The top-level beans element allows you to switch autowiring on or off for the entire context. Using this feature, the only thing you need to do if you define a new bean is add it to the context. Dependencies will then be automatically satisfied. If you go into production however, I suggest you change the remove the default autowiring attribute and make all dependencies explicit though bean references since they provide excellent documentation on how the application is assembled from its individual components.

There’s more where that came from

I hope I’ve shown you some features Spring has that will allow you to create more consistent and readable XML. There are certainly more interesting ways to keep the XML manageable. Be sure to check the reference documentation and the Spring Beans DTD for more info on how Spring XML works.

XML simplification coming in Spring 1.3

I promised to also shortly talk about our plans to include a major enhancement to the way Spring handles XML files to create beans. After a lot of discussion, we’ve finally got to a decent approach to allow for extending Spring’s XML format. To be able to target more specific use cases and to let the XML focus on more than just dependency injection, we’re about to implement some code that will allow you to do the following:

<j2ee :jndi id="dataSource"
  refName="java:comp/env/jdbc/MyDataSource"/>

to create a reference to a JNDI-based DataSource instead of

<bean class="org.sprfr.jndi.JndiObjectFactoryBean">
  <property name="jndiName" 
    value="java:comp/env/jdbc/MyDataSource"/>
</bean>

and

<instance :pooled id="parser" class="example.DocumentParser">
  <property name="myConfigProperty" value="1"/>
</instance>

to create a pooled version of the DocumentParser bean intead of the much more verbose XML fragment shown below.

<bean id="parser"
  class="org.sprfr.aop.framework.ProxyFactoryBean">
  <property name="targetSource" 
    ref="commonsPoolTargetSource"/>
</bean>
 
<bean id="commonsPoolTargetSource" 
  class="org.sprfr.aop.target.CommonsPoolTargetSource">
  <property name="maxSize" value="30"/>
  <property name="targetBeanName" value="parserTarget"/>
</bean>
 
<bean id="parserTarget" class="example.DocumenParser"/> 

We still have to work out how this will work in detail but the first test cases have been completed successfully and to be honest, I’m pretty excited about this. The pooling example by the way has been taken from my previous entry on instance management.

p.s. For readers that know me: no I did not all of sudden get children, and if I had children, I certainly wouldn’t have named them Peggy and Ricky.

Written by Alef in: Java-related, Spring |
Jul
06
2005
1

Ajax in Action (part III)

A couple of months ago I posted a (fake) announcement for Ajax in Action, a book on the cool new tech. that I cynically positioned as being hyped a bit. At the time I couldn’t imagine that in fact Manning was really going to publish a book called Ajax in Action. Unfortunately no greek image of the god called Ajax on the cover :( .

Here’s a link to the book. http://www.manning.com/books/crane.

Written by Alef in: Java-related |
Jul
06
2005
24

Spring instance management part I – pooling

In two previous posts, I covered the FactoryBean and the basic instantiation strategies Spring offers. This post and some of the following will focus on other strategies Spring offers to manage instances of your objects. In a future post we’ll also have a look at a custom implementation of an extension point Spring offers to manage the way Spring gets to your objects.

This post is by the way followed up by a second one on performance, mixins and hotswapping.

Solutions to real-world problems

First all we should be clear on when to use the different instantiation strategies avaible. Why use anything other the Spring singleton or prototype mode if it doesn’t provide any real value! We’ll look at a number of different problems and review how we can solve each of them.


Multi-threaded XML parsing


In an application we built last year for a customer of ours, a portal application queries a backend for information. The backend returns XML which in its turns, needs to be parsed and rendered to the client. A SAX parser took care of the parsing. The site gets heavy loads (up to 50 requests per second, which all cause multiple backends to be queried). A lot of the functionality we developed for the portal was placed in Spring-managed singletons. Obviously instantiating a new SAX parser per XML document the backend returned was out of the question as was using just one SAX parser. We really needed a pooling strategy here.

Situations like the above where in a multi-threaded environment you need non-thread-safe resources that are expensive to instantiate, provide an excellent case for pooling. Consider the following helper class that ‘does something’ to an InputStream, resulting in a PortalDocument.

public class DocumentParser {
 
  // setters, getters and initializing methods
 
  public PortalDocument parse(InputStream is) {
    // non-thread-safe implementation goes here
  }
}

Wiring the document parser as follows, with a thread-safe PortalManager, would result in a situation where only one instance of the singleton document parser is available, and thread-safety is not guaranteed:

<bean id="parser" class="example.DocumentParser"/>
 
<bean id="portalManager" class="example.PortalManager">
  <property name="documentParser" ref="parser"/>
</bean>

Fortunately, Spring provides a pooling strategy that allows you to transparently pool the document parser, without changing any code.

Code managing the instances of your objects and controlling how many of them are available is infrastructural code which you 1) shouldn’t have to write and 2) should not intermingle with your normal application code.

Shortly introducing the ProxyFactoryBean

Pooling makes use of the Spring AOP framework and to better understand the approach Spring uses, we first have to have a look at the Spring ProxyFactoryBean, one of the cornerstones of the Spring AOP framework. The ProxyFactoryBean wraps objects and ‘decorates’ them with additional behavior (so-called advices). The actual object being wrapped is called the target. The following for example wraps an instance of the DocumentParser and adds debug behavior to it:

<bean id="parser" 
    class="org.sprfr.aop.framework.ProxyFactoryBean">
  <property name="target">
    <bean class="example.DocumentParser"/>
  </property>
  <property name="interceptorNames" 
    value="debugInterceptor"/>
</bean>
 
<bean id="debugInterceptor" 
  class="org.sprfr.aop.interceptor.DebugInterceptor"/>

The TargetSource

The ProxyFactoryBean features another interesting concept called a target source. The Spring proxy factory bean can delegate (after for example debug messages have been output to Log4J) to either the target (as wired up in the example above) or to an object obtained from a target source. So in other words:

An invocation to a Spring proxy (after passing through the behavior that has been added by the proxy factory bean) will either be delegated to the target object specified while creating the factory bean or to an object the proxy has obtained from the org.springframework.aop.TargetSource.

The pooling target source

The simplest TargetSource that is available is the SingletonTargetSource, which (as the class name might indicate) holds a singleton to delegate method calls to. There are however a number of other target sources available, of which we’ll review the AbstractPoolingTargetSource (and the accompanying CommonsPoolTargetSource) in this article.

The use case we’re having can easily be described in pseudo-code:

  1. Execute request on backend
  2. Receive InputStream from backend
  3. Obtain DocumentParser from pool
  4. Parse the data from the InputStream
  5. Give the object back to the pool

In the next section, we’re going to remove step 3 and 5 by using a TargetSource. Remember, pooling is one of those things you don’t want to code yourself and should be part of the infrastructure of your application.

Instead of wiring the target itself as we just learned, we need to wire a target source, more specifically, a CommonsPoolTargetSource. This is what the ProxyFactoryBean will obtains its delegate from. The CommonsPoolTargetSource uses Commons Pool under the covers and it mirrors a lot of configuration methods from the Commons Pool such as the maxmimum amount of objects that can be created. Let’s wire a pooling target source that will hold a maxmimum of 30 DocumentParsers.

<bean id="commonsPoolTargetSource" 
  class="org.sprfr.aop.target.CommonsPoolTargetSource">
  <property name="maxSize" value="30"/>
  <property name="targetBeanName" value="parserTarget"/>
</bean>
 
<bean id="parserTarget" class="example.DocumentParser" singleton="false"/>

Since we’ve now wired up our target source, we’re ready to create the ProxyFactoryBean. Remember, this time we’re going to use the newly created target source instead of simply wiring the target itself.

<bean id="parser"
  class="org.sprfr.aop.framework.ProxyFactoryBean">
  <property name="targetSource" 
    ref="commonsPoolTargetSource"/>
</bean>
 
<bean id="portalManager"
  class="example.PortalManager"
  <property name="documentParser" ref="parser"/>
 

After we’ve injected the ProxyFactoryBean with the correct target source, we’re done! Essentially, the above configuration results in the following if the PortalManager calls the parse() method from the DocumentParser:

  1. Proxy receives method call parse()
  2. Proxy obtains target object from Commons Pool target source
  3. Proxy delegates method call to target object
  4. DocumentParser.parse(InputStream) gets called and returns PortalDocument
  5. Proxy returns target object (DocumentParser) to the Commons Pool
  6. Proxy returns PortalDocument to caller

Catches

The most important thing happening in the process described above is the method call being executed on the proxy. Upon a method call Spring retrieves an object from the pool and after the method has returned it is put back in the pool. Remember that for two different method calls, you are not guaranteed to get the same instance. So if, next to the parse(), there would for example be an additional method (e.g. validate()) don’t count on the the two consecutive method calls to be executed using the same target.

Conclusion

In this article, we’ve reviewed what facilities Spring offers to add a level of indirection to the obtaining of the target a proxy will delegate calls to. Using the TargetSource we’ve added pooling behavior to our non-thread-safe DocumentParser class without having to change any of the underlying code. Using a different (maybe more sophisticated) pooling algorithm, or maybe removing the pooling behavior is now a matter of changing around some configuration XML.

Spring reference manual (and more specifically, Chapter 5) offers more insight into Spring’s AOP framework and ways you can use it to transparently ‘decorate’ your POJOs.

In the next article, we’ll see how we can use an additional feature of the Spring AOP framework (introduction) to get some statistical data about the pool. We’ll also have a look at other cases where Spring can manage expensive resources in an efficient an non-invasive way.

Update: changed incorrect bean reference with target source definition to point to the parserTarget bean.

Written by Alef in: Java-related, Spring |
Jul
03
2005
10

Spring instantiation strategies

In relation to my previous post I’d like to shortly discuss the different instantiation methods Spring supports. We’ve reviewed the concept of a FactoryBean in detail, but there’s way more you should know about how Spring creates instances of types wired up in your context.

Prototypes and singletons

The most important characteristic for a bean definition in a Spring context is whether or not the bean is a singleton. Tweaking the singleton attribute is the way to specify this characteristic:

<bean class="example.MyObject" singleton="false"/>

versus

<bean class="example.MyObject" singleton="true"/>

You have to keep one thing in mind about Spring singletons:

Beans defined as singletons in a Spring ApplicationContext, are singletons only in the scope of the ApplicationContext you’ve defined the bean in.

In other words, if I have two distinct application contexts both having defined a singleton bean, each context will contain exactly one instance of the singleton. This is different from the way we implemented singletons in Java usually, using a static getInstance() method along with a private constructor to prevent instantiation. Here, there will be one instance of the bean per VM or better, per distinct ClassLoader sibling the singleton class was loaded in.

Als note that by default a bean in a context is a singleton, so you don’t have to specify singleton="true" with every bean.

It’s good practice to develop your code in a thread-safe way. There’s no reason to resort to changing your beans to prototypes or even use things like instance pooling unless you’ve really need it!

Ways Spring instantiates your objects

And now for the real meat: how does Spring actually instantiate your objects. Spring is designed for use with all objects of all types your can think of. Using one of the following instantiation methods, you should be able to wire almost any Spring bean in your context, whether it are legacy objects that need special treatment or plain and simple JavaBeans with a no-args constructor. As far aas I know there’s only one type of object you can’t instantiate. I’ll talk about that a bit near the end of this post.

In the example listed below, we’ll be using the Spring ApplicationContext.getBean() call to show the behavior of the different methods we have. Usually, you don’t have to resort to using the ApplicationContext API, but for demonstration purposes it works pretty well here. Remember that under the covers obtaining beans, dependency injecting beans into other beans all boils down to Spring using the getBean() method on the ApplicationContext. In other words, the following would result in two distinct calls to ApplicationContext.getBean("testBean"). Because we didn’t specify the singleton attribute, Spring will make this bean a singleton (remember, this is the default behavior) and although there are two calls to getBean() for this specific bean identifier, there will be only one instance of the bean.

<bean id="testBean" class="example.TestBean"/>
 
<bean id="anotherBean" 
    class="example.AnotherBean">
  <property name="collaborator" ref="testBean"/>
</bean>
 
<bean id="yetAnotherBean" 
    class="example.YetAnotherBean">
  <property name="collaborator" ref="testBean"/>
</bean>

Let’s review (a really simplified almost pseudo-code version of) what Spring does behind the scenes as well:

ApplicationContext ctx = new ApplicationContext();
TestBean mySingleton = new TestBean();
ctx.addBean(mySingleton);
 
AnotherBean ab = new AnotherBean();
TestBean collForAb = ctx.getBean("testBean");
// retrieve test bean for use as collaborator
ab.setCollaborator(collaboratorForAb);
 
YetAnotherBean yab = new YetAnotherBean();
// same reference as collForAb since it's a singleton
TestBean collForYab = ctx.getBean("testBean");
yab.setColllaborator(collaboratorForYab);

If we would have set the singleton attribute to false we would have gotten two different instances of the TestBean class!

Note that the above is a really simplified version of what Spring does behind the scenes. It is just to show how Spring works and let you understand how to work with all the different instantiation methods. If you try to compile this code, it won’t even work.

Using a no-args constructor

In my my previous post we already shortly discussed setter injection and using a no-args constructor. The most well-known way Spring instantiates your objects is using a JavaBean-style no-args constructor. Consider the following:

public class NoArgsConstr {
  public NoArgsConstr() {
  }
}
<bean id="noArgs" class="example.NoArgsConstr"/>

The above example roughly translates to the following:

NoArgsConstr myBean = new NoArgsConstr();
ctx.addBean(myBean);

As we’ve seen before, the noArgs bean is defined as a singleton (since this is the default behavior) and therefore every call to ApplicationContext.getBean("myBean") (hence every reference you create to the bean in your context) will result in the exact same instance to be returned or referenced.

Other than no-args constructor

You can also use constructors that do take arguments. The following illustrates how this works:

class OtherConstr {
  public OtherConstr(int a, String b) {
    // do something with a and b
  }
}
<bean id="otherConstr" class="example.OtherConstr">
  <constructor -arg index="0" value="1"/>
  <constructor -arg index="1" value="alef"/>
</bean>

And as you would expect this will result in a bean being added to the context created by issuing the new OtherConstr(1, "alef") statement. Note that Spring automatically detects the types of your constructor arguments and property values (unless you specifically specify the type attribute).

Using a static factory method

In yesterday’s post we’ve seen that using FactoryBeans you can instantiate all kinds of objects that might not have a public constructor. One of those might be types with a static factory method. There’s a shortcut to obtaining instances of beans with static factory methods. Using the factory-method method attribute in combination with the class attribute, Spring will create the bean using the method and class you’ve specified. Consider the following class:

class MyClass {
 
  MyClass() { }
 
  public void applyRandom(Random r) {
    // do something with random
  }
 
}

The following factory creates an instance of MyClass:

class MyClassFactory {
 
  private MyClassFactory() {}
 
  public static MyClass createMyClass(
      long seed) {
    MyClass myClass = new MyClass();
    Random r = new Random(seed);
    myClass.applyRandom(r);
    return myClass;
  }
}

If you want to use the MyClass bean in combination with the factory, you’d have to use the following in your Spring context:

<bean id="myFactory" 
  class="example.MyClassFactory
  factory-method="getInstance">
  <constructor -arg value="12345"/>
</bean>

Note that using the constructor-arg elements will cause the values to be passed to the factory method you’ve specified whereas any nested property elements will be applied to the object the factory method returns.

Using a factory method from a different bean

Where the factory-method in combination with a class attribute would cause Spring to call a static factory method on the class specified, in combination with the factory-bean attribute the factory method will have to be defined on another bean defined in your context. This allows you to configure the factory as well using Spring DI. Consider the following rewritten example (the same MyClass object is used here, the factory differs a bit):

class MyClassFactory {
 
  public MyClassFactory(long seed) {
    this.random = new Random(seed);
  }
 
  public MyClass createMyClass() {
    MyClass myClass = new MyClass();
    myClass.applyRandom(random);
    return myClass;
  }
}

The following XML fragment would cause Spring to first instantiate the MyClassFactory and register it as a bean in the context. The second thing it would do is call the createMyClass() on that same bean and register the result in the context as well:

<bean id="myFactory" class="example.MyClassFactory">
  <constructor -arg value="12345"/>
</bean>
 
<bean id="myClass"
  factory-bean="myFactory"
  factory-method="createMyClass"/>

Note that with this option, you can specify arguments to pass to the factory method as well. Just as above, you’d have to use the constructor-arg elements along with the myClass bean.

FactoryBeans

Another way to instantiate your beans is using the FactoryBean interface. I won’t be discussing this here in more detail.

Things to consider when using different instantiation strategies

Although all the instantiation strategies are nicely supported, you shouldn’t use them when creating new classes. Be sure not to design your classes using a factory method of some sort if you don’t know why you’re actually doing it. The instantiation strategies are part of Spring because we’d like you to wire up any object of any type including objects not created by yourself.

Another thing yo keep in mind when using factory methods for example is the singleton aspect of Spring beans. The following for example, would not cause multiple SingletonBeans to be available in the context, since the factory method we’re using in fact returns a singleton itself. So setting the singleton attribute to false here in fact doesn’t work!

class SingletonBean {
  private SingletonBean instance = new SingletonBean();
  public static getInstance() {
    return instance;
  }
}
<bean id="mySingleton"
  class="example.SingletonBean"
  factory-method="getInstance"
  singleton="false"/>

Protected constructors

Spring has the option to instantiate beans with a protected constructor. Using the setAccessible(true) method on a constructor, Spring is still able to instantiate your beans. Don’t design your classes with a protected constructor! Again, this option is meant to solve situations where you don’t have control over the class you want to wire up.

The one bean you can’t wire up in Spring

As far as I know there are very little situations where you can’t use one of the above instantiation strategies to wire a bean into a Spring context. The only situation I can think of right now is (apart from a class with a private constructor and no getInstance() method–but those classes can’t be instantiated anyway):

  • A class with a package friendly constructor
  • in a package which is sealed
  • with a security policy which doesn’t allow setAccessible(true)
Written by Alef in: Java-related, Spring |

Powered by WordPress | Theme: Aeros 2.0 by TheBuckmaker.com