Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Wednesday, August 4, 2010

Prototypes, Lookup Methods and Java Config With Spring...

Referencing a Prototype from a Singleton in Spring:

Sometimes in Spring, you need to create a one-time use instance that has state (a.k.a a prototype bean) from a Singleton object. Essentially, one would need to access a prototype for a number of cases, namely those where the Gang of Four Abstract Factory can be applied :

  • You have an object that requires complex construction

  • You have many potential implementations of an interface, and generic logic that applies to all of those implementations.

    Spring's documentation for prototype scope and method injection lets you know that you can accomplish that goal in the following manner:

                  

    where your commandManager looks something like:

    package fiona.apple;  // no more Spring imports! `public abstract class CommandManager {   public Object process(Object commandState) {     // grab a new instance of the appropriate Command interface     Command command = createCommand();     // set the state on the (hopefully brand new) Command instance     command.setState(commandState);     return command.execute();   }    // okay... but where is the implementation of this method?   protected abstract Command createCommand(); }

    You have a generic business object/singleton (CommandManager) that need to create an implementation of an interface with state to perform some task.

    I personally found it useful for a couple of scenario in a large scale website projects. Overall, this approach served me well when I needed it, and was pretty painless.

    Constructive Criticism

    While the "lookup-method" trick is definitely useful, it definitely doesn't feel right. Bob Lee criticised Spring for having to put method names in XML (although I can't find a reference to the specific entry in which he does it). I don't know if the criticism was meant for this specific instance, but the criticism definite applies. This definitely feels like you're coding in XML. Programming in XML isn't pretty. The XML configuration in Spring is getting the more and more complex, although for now, it doesn't get to complicated.

    This coding through XML isn't purely a "feel" issue. What happens if you change the method name? Why should you have to wait until runtime to catch typos?

    Spring 2.5 theoretical @LookupMethod

    I don't think that the new Spring annotations solve the -> problem, but I assume that it could. Here's how it could look:

    package fiona.apple;  // no more Spring imports... except for spring annotations  @Component public abstract class CommandManager {   public Object process(Object commandState) {     // grab a new instance of the appropriate Command interface     Command command = createCommand();     // set the state on the (hopefully brand new) Command instance     command.setState(commandState);     return command.execute();   }    @LookupMethod(beanName="command")   protected abstract Command createCommand(); }

    This has a lot of advantages: it's very terse and shows you all about how a class is used right along with the implementation of the class. The disadvantage here, is that you're adding dependencies on Spring via the annotations. Also, you can't configure different instances of the "Singleton" with different implementations of the prototype... (I'm not sure what to call the multi-Singleton... Multiton?)

    Spring JavaConfig's approach

    I've been thinking about and even working on Spring JavaConfig (SJC) for a while. Take a look at this SJC bugthat talks about lookup methods. The way you'd implement "lookup methods" in a java oriented environment is quite straight forward. The bean stays the same:

    package fiona.apple;  // no more Spring imports! public abstract class CommandManager {   public Object process(Object commandState) {     // grab a new instance of the appropriate Command interface     Command command = createCommand();     // set the state on the (hopefully brand new) Command instance     command.setState(commandState);     return command.execute();   }    // okay... but where is the implementation of this method?   protected abstract Command createCommand(); }

    The configuration code is surprisingly simple:

    package fiona.apple;  // a whole bunch of spring and business object imports  @Configuration public class CommandManagerConfiguration {     @Bean    public CommandManager commandManager(){       return new CommandManager(){          protected Command createCommand(){            /* you can add your dependencies here,               if you have any */             return new AsyncCommand();          }       };    }  }

    A Java based configuration is, IMHO, a much more natural implementation than the XML approach. This is a surprisingly trivial implementation of a relatively complicated scenario.

    The slickness here comes from writing simple Java code

    SJC beyond prototypes

    The prototype slickness lead me down a path that helped me shed the preconceived notions that came from XML-based development. I started thinking about where I could use java to make my application configuration process even better. Now, I definitely thought of some cool infrastructure stuff that I could add to Spring JavaConfig, but that's not the application configuration ingredients that I find most interesting.

    The most interesting techniques a programmatic environment can add to application construction come from really simple day-to-day java code. For example, you can create conditional beans using a simple "if" statement. You can concatenate Lists and Maps. Those examples, plus other simple programming techniques that we've come to depend on as second nature, are now available. Spring doesn't dictate what I can do when constructing an application. You can now use Plain Old Java to configure your Plain Old Java Objects.

    Some of the more esoteric techniques I thought of included 1) finding an easy hook that allows programmatic bean creation using Spring's underlying application configuration meta data objects, and 2) allowing users to hook in their own configuration Annotations.

    Conclusions

    I hope that this blog entry will be useful for two purposes:

    1. Describe how and why Spring creates prototype objects within singleton beans

    2. Give an idea about how Spring JavaConfig can help with

    You'll see some fantastic things from Spring JavaConfig soon... In the mean time, there's definitely plenty of goodies that you can get out of traditional, and main-stream spring xml configuration and java annotations.

  • Unit Testing from the trenches

    Unit testing is one of the cornerstones of modern software development. Working on several projects with Spring and Hibernate I have come to the conclusion that (in that setting?) there are actually three types of unit testing:

    1. Basic Unit testing
    2. Dao Layer Unit testing
    3. Component Integration testing

    As the name of the last type suggests, the categories are actually on a scale towards integration testing. This leads to the conclusion that the boundaries between unit and integration testing are not very sharp. This is interesting, since in our build systems (maven) and best practices, the two are distinct steps.

    In this blog I’ll discuss the differences between the three types and describe some guidelines for creating tests.

    Basic Unit testing


    Basic unit testing is where you test the smallest units in your system in isolation. The units are usually single classes, in rare cases a class can be considered a sub unit of another class not worthy of a separate test. In my experience a satisfactory level of isolation can only be achieved by mocking. The reason for this is that only mocking ensures that when the functionality of a class changes, the change doesn’t cascade through the tests for all classes using that functionality. This is what isolation is all about. We use RMock, although rumor has it that on a Java5 enabled project the latest version of EasyMock would be superior.

    A serious drawback of this approach, in my opinion, is that it doesn’t really inspire TDD. One of the basics ofTDD is that the design of the solution should follow from the test and the test should follow directly from a requirement. Most requirements are not easily interpreted as “add this functionality to this class”. To arrive at the class level, some (upfront) design is necessary. So instead of writing a test that encapsulates the requirement, the requirement is broken down into functionality that is assigned to classes (this is the upfront design) and this functionality is tested.

    DAO layer testing


    When using Hibernate or any other framework for your DAO layer, a lot of business logic ends up in units or artifacts that are not testable by basic unit testing. With Hibernate the business logic gets injected into the mapping files and the queries.
    Hibernate mappings basically allow the application to do CRUD operations on entities. A basic test would start with inserting an entity, check that it can be retrieved, update it, check again and then delete it. Envisioning a test framework for this is not that hard. But Hibernate configuration files also define complex properties such as cascading and inverse-ness. Correct configuration of these properties is just as important in your application. Testing these properties is a bit more complicated, involving navigating associations and collections.

    Testing queries is a bit more complicated. Based upon an HQL, SQL or Criteria query, Hibernate generates SQL that can be executed against a specific RDBMS. One approach towards testing the query would be checking that the generated query is correct. This involves parsing the SQL produced and then checking certain features, such as the presence of tables in the FROM-clause, the correct restrictions in the WHERE-clause and the columns in the SELECT clause. This seems pretty laborious. Another approach would be to actually execute the SQL against a database and check the results. Using an in memory database such as HSQLDB, this is quite an easy task. One important side effect of this is that Hibernate will generate different SQL for a different type of RDBMS. When the test setup uses a different type of RDBMS, the queries that are used in the deployed situation are actually never tested during the unittest phase.

    Data is another problem when running tests against an actual RDBMS. To be able to check the logic of a query, it should be executed against a number of different datasets. Usually the query is sensitive to parameters as well as to the actual data in the system. Both sensitivities should be tested with different variations. One way of getting data in to the system to enable testing is using DBUnit. This framework reads XML files and creates insert statements that can be executed against the RDBMS. The problem with this approach is that test expectations and results for different tests tend to get correlated, since the data for the whole test case is read from the same XML file. This file tends to get very big and hard to understand, the different variations that are tested are hardly documented and not evident from a quick scan of the file.

    One solution would be to use a separate file for each test. In this situation, tests will not be correlated and a comment at the top of the file could describe the variation that is tested. This would probably lead to a large number of very similar files in the project. Due to foreign key restrictions, inserting a single record in the database often cascades through a lot of related tables that are reference data. This could be resolved by using a hierarchical structure, in which reference data is loaded first and used with a number of smaller and more specific datasets.

    A different solution would be to create the objects necessary for the test in the code end persist them using Hibernate. The resulting tests would be easier to refactor and would be more independent. It could lead to a lot of code duplication, but this might be solved by using the ObjectMother Pattern. An extra advantage of this approach would be that the mapping files are tested indirectly. This might actually be a bad thing, since when a mapping is corrupted, completely unrelated tests might fail.

    As always, reality isn’t simple and the best solution will be a mix of both. I’ve actually never tried mixing both strategies (DBunit and ObjectMother) on the same project. I’m very curious what the pitfalls will be. A problem that will probably remain with every strategy is that test coverage cannot be determined (or can it?).

    Component Integration testing


    When using Spring, units are glued together in an application context into ‘components’ or top level beans. The application context is never really used in the unit test phase, since its sole purpose is glueing together units that are tested in isolation in this phase. The application context is one of the most important files in your application. Starting up an application with a typo in its application context will fail miserably, though luckily early.

    Some of the properties and structures that are defined in the application context can have a far reaching impact on your application. Usually transaction boundaries are defined here and other cross-cutting concerns as well. Not testing the application context should in my opinion be considered a serious shortcoming of the automatic testing of an application. Some of the components that are used in the deployed situation (and thus configured in the application context) cannot be used in a test situation. An example of these are interfaces to backend systems. To facilitate this, these components should be defined in a separate application context, that can be left out or replaced when testing.

    On the other hand, these type of tests are very similar to integration tests. I think the difference should be that the “Component Integration” tests hardly check the results of the application. If a certain service method can be executed without running into a NullPointerException and it outputs something that at first glance appears to be meaningful, the test has succeeded. Further testing should be considered part of the functional and integration tests.

    Conclusion


    In my opinion there are several steps that should be executed sequentially in the unit test phase. A failure in an early step should terminate the building process without executing the other steps, since their erroneous output might rely on the previously found error. One of my colleagues suggested TestNG to create test groups. The types of tests described above can be used as starting points for these steps. There might be other types of tests that deserve their own group. The methods described above to write the tests seem promising, but are not yet proven technology. Do you think the grouping of unittests is useful? Do you recognize the groups and guidelines described above?

    Twelve Best Practices For Spring XML Configurations

    Spring is a powerful Java application framework, used in a wide range of Java applications. It provides enterprise services to Plain Old Java Objects (POJOs). Spring uses dependency injection to achieve simplification and increase testability. Spring beans, dependencies, and the services needed by beans are specified in configuration files, which are typically in an XML format. The XML configuration files, however, are verbose and unwieldy. They can become hard to read and manage when you are working on a large project where many Spring beans are defined.

    In this article, I will show you 12 best practices for Spring XML configurations. Some of them are more necessary practices than best practices. Note that other factors, such as domain model design, can impact the XML configuration, but this article focuses on the XML configuration's readability and manageability.

    1. Avoid using autowiring


    Spring can autowire dependencies through introspection of the bean classes so that you do not have to explicitly specify the bean properties or constructor arguments. Bean properties can be autowired either by property names or matching types. Constructor arguments can be autowired by matching types. You can even specify the autodetect autowiring mode, which lets Spring choose an appropriate mechanism. As an example, consider the following:

    id="orderService" class="com.lizjason.spring.OrderService" autowire="byName"/>

    The property names of the OrderService class are used to match a bean instance in the container. Autowiring can potentially save some typing and reduce clutter. However, you should not use it in real-world projects because it sacrifices the explicitness and maintainability of the configurations. Many tutorials and presentations tout autowiring as a cool feature in Spring without mentioning this implication. In my opinion, like object-pooling in Spring, it is more a marketing feature. It seems like a good idea to make the XML configuration file smaller, but this will actually increase the complexity down the road, especially when you are working on a large project where many beans are defined. Spring allows you mix autowiring and explicit wiring, but the inconsistency will make the XML configurations even more confusing.

    2. Use naming conventions


    This is the same philosophy as for Java code. Using clear, descriptive, and consistent name conventions across the project is very helpful for developers to understand the XML configurations. For bean ID, for example, you can follow the Java class field name convention. The bean ID for an instance of OrderServiceDAO would be orderServiceDAO.For large projects, you can add the package name as the prefix of the bean ID.

    3. Use shortcut forms


    The shortcut form is less verbose, since it moves property values and references from child elements into attributes. For example, the following:

    id="orderService" class="com.lizjason.spring.OrderService">
    
    name="companyName">
    lizjason


    bean="orderDAO">


    can be rewritten in the shortcut form as:

    id="orderService" class="com.lizjason.spring.OrderService">
    
    name="companyName" value="lizjason"/>
    ref="orderDAO"/>

    The shortcut form has been available since version 1.2. Note that there is no shortcut form for .

    The shortcut form not only saves you some typing, but also makes the XML configuration files less cluttered. It can noticeably improve readability when many beans are defined in a configuration file.

    4. Prefer type over index for constructor argument matching


    Spring allows you to use a zero-based index to solve the ambiguity problem when a constructor has more than one arguments of the same type, or value tags are used. For example, instead of:

    id="billingService" class="com.lizjason.spring.BillingService">
    
    index="0" value="lizjason"/>
    index="1" value="100"/>

    It is better to use the type attribute like this:

    id="billingService" class="com.lizjason.spring.BillingService">
    
    type="java.lang.String" value="lizjason"/>
    type="int" value="100"/>

    Using index is somewhat less verbose, but it is more error-prone and hard to read compared to using the type attribute. You should only use index when there is an ambiguity problem in the constructor arguments.

    5. Reuse bean definitions, if possible


    Spring offers an inheritance-like mechanism to reduce the duplication of configuration information and make the XML configuration simpler. A child bean definition can inherit configuration information from its parent bean, which essentially serves as a template for the child beans. This is a must-use feature for large projects. All you need to do is to specify abstract=true for the parent bean, and the parent reference in the child bean. For example:

    id="abstractService" abstract="true" class="com.lizjason.spring.AbstractService">
    
    name="companyName" value="lizjason"/>


    id="shippingService" parent="abstractService" class="com.lizjason.spring.ShippingService">
    name="shippedBy" value="lizjason"/>

    The shippingService bean inherits the value lizjason for the companyName property from the abstractService bean. Note that if you do not specify a class or factory method for a bean definition, the bean is implicitly abstract.

    6. Prefer assembling bean definitions through ApplicationContext over imports


    Like imports in Ant scripts, Spring import elements are useful for assembling modularized bean definitions. For example:

    
    
    resource="billingServices.xml"/>
    resource="shippingServices.xml"/>
    id="orderService" class="com.lizjason.spring.OrderService"/>

    However, instead of pre-assembling them in the XML configurations using imports, it is more flexible to configure them through the ApplicationContext. Using ApplicationContext also makes the XML configurations easy to manage. You can pass an array of bean definitions to the ApplicationContext constructor as follows:

    String[] serviceResources = {"orderServices.xml", "billingServices.xml",
    
    "shippingServices.xml"};

    ApplicationContext orderServiceContext = new ClassPathXmlApplicationContext(serviceResources);

    7. Use ids as bean identifiers


    You can specify either an id or name as the bean identifier. Using ids will not increase readability, but it can leverage the XML parser to validate the bean references. If ids cannot be used due to XML IDREF constraints, you can use names as the bean identifiers. The issue with XML IDREF constraints is that the id must begin with a letter (or one of a few punctuation characters defined in the XML specification) followed by letters, digits, hyphens, underscores, colons, or full stops. In reality, it is very rare to run into the XML IDREF constraint problem.

    8. Use dependency-check at the development phase


    You can set the dependency-check attribute on a bean definition to a value other than the default none, such as simple, objects, or all, so that the container can do the dependency validation for you. It is useful when all of the properties (or certain categories of properties) of a bean must be set explicitly, or via autowiring.

    id="orderService" class="com.lizjason.spring.OrderService" dependency-check="objects">
    
    name="companyName" value="lizjason"/>
    ref="orderDAO"/>

    In this example, the container will ensure that properties that are not primitives or collections are set for the orderService bean. It is possible to enable the default dependency check for all of the beans, but this feature is rarely used because there can be beans with properties that don't need to be set.

    9. Add a header comment to each configuration file


    It is preferred to use descriptive ids and names instead of inline comments in the XML configuration files. In addition, it is helpful to add a configuration file header, which summarizes the beans defined in the file. Alternatively, you can add descriptions to the description element. For example:

    
    

    This file defines billing service
    related beans and it depends on
    baseServices.xml,which provides
    service bean templates...

    ...

    One advantage of using the description element is that it is easy to for tools to pick up the description from this element.

    10. Communicate with team members for changes


    When you are refactoring Java source code, you need to make sure to update the configuration files accordingly and notify team members. The XML configurations are still code, and they are critical parts of the application, but they are hard to read and maintain. Most of the time, you need to read both the XML configurations and Java source code to figure out what is going on.

    11. Prefer setter injection over constructor injection


    Spring provides three types of dependency injection: constructor injection, setter injection, and method injection. Typically we only use the first two types.

    id="orderService" class="com.lizjason.spring.OrderService">
    
    ref="orderDAO"/>


    id="billingService" class="com.lizjason.spring.BillingService">
    name="billingDAO" ref="billingDAO">

    In this example, the orderService bean uses constructor injection, while the BillingService bean uses setter injection. Constructor injection can ensure that a bean cannot be constructed in an invalid state, but setter injection is more flexible and manageable, especially when the class has multiple properties and some of them are optional.

    12. Do not abuse dependency injection


    As the last point, Spring ApplicationContext can create Java objects for you, but not all Java objects should be created through dependency injection. As an example, domain objects should not be created through ApplicationContext. Spring is an excellent framework, but, as far as the readability and manageability are concerned, the XML-based configuration can become an issue when many beans are defined. Overuse of dependency injection will make the XML configuration more complicated and bloated. Remember, with powerful IDEs, such as Eclipse and IntelliJ, Java code is much easier to read, maintain, and manage than XML files!

    Conclusion


    XML is the prevailing format for Spring configurations. XML-based configuration can become verbose and unwieldy when many beans are defined. Spring provides a rich set of configuration options. Appropriately using some of the options can make the XML configurations less cluttered, but other options, like autowiring, may reduce readability and maintainability. Following good practices discussed in the article may help you to create clean and readable XML configuration files!

    Configuration-hell remedy with Singleton injection

    One of the most heard complaints about Spring projects is the seemingly unavoidable configuration-hell that silently creeps in every bigger project after some time.
    Singleton injection is a simple practice that can significantly reduce configuration and corresponding injection code. Besides that, it provides possibilities you might not have been aware of enabling you to get most out of Spring. In this blog you will learn which advantages Singleton injection provides. It illustrates how to implement it and specifies clear guidelines in which circumstances it is applied best.
    Where applicable, Singleton injection can be an elegant solution that provides significant code and configuration simplification.
    At the beginning of a Spring project, when the applicationContext.xml(s) resemble a fallow field, it is easy to keep the overview of your beans. As time goes by most of us have been facing the configuration-hell growing out of proportion, making it difficult to find your way in the bean jungle. There are several commonly applied best-practices to postpone this problem as long as possible, such as the usage of abstract declarations, splitting up the bean configuration in several subconfigurations or Eclipse’s Spring IDE.
    Besides that I have come across another way, which can significantly contribute to reduce spring configuration, eliminate superfluous code and provide other interesting advantages you might not have been aware of before. The way to achieve that is called Singleton injection.

    The familiar way

    Consider the following piece of code and configuration:
    public class AnyService {
    
    private Logger log = Logger.getLogger(AnyService.class);
    private MessageResource messageResouce;

    public setMessageResource(MessageResource messageResouce) {
    this.messageResouce = messageResouce;
    }
    public void execute() {
    if(condition)
    log
    .error(messageResource.getMessage("error.msg.key.1"));
    // more code
    }
    }

    public class AnyDAO {
    private Logger log = Logger.getLogger(AnyDAO.class);
    private MessageResource messageResouce;

    public setMessageResource(MessageResource messageResouce) {
    this.messageResouce = messageResouce;
    }

    public List findAll() {
    if(condition)
    log
    .warn(messageResource.getMessage("error.msg.key.2"));
    //more code
    }
    }
    
    

    id="messageResource" class="com.xebia.example.MessageResourceImpl">
    property name="resourceLocation" value="classpath:/bundle.properties"/>



    id="aService" class="AnyService">
    name="messageResource" ref="messageResource"/>

    id="aDAO" class="AnyDAO">
    name="messageResource" ref="messageResource"/>

    Apparently, the MessageResource class is used throughout the application, actually by each class that needs to log something. Since we want to initialize the MessageResource class with the proper configuration with the BeanFactory facilities, we configure the MessageResource class as a spring bean and inject it in every class that makes use of it. The latter is followed by tedious instance variable/setter code and injection configuration. This should sound familiar to you.

    The alternative: Singleton injection

    Fortunately, there is an easier way. Consider the following piece of code:
    public class AnyService {
    
    private Logger log = Logger.getLogger(AnyService.class);

    public void execute() {
    if(condition)
    Log.error(MessageResourceSingleton.getInstance().getMessage(“error.msg.key.1”));
    // more code
    }
    }
    As you can see, most of the spring-related injection hassle seems to have disappeared. At least, that might be the first impression. Instead of cumbersomely injecting the MessageResource bean in all classes that use it, we take a slightly different approach:
    1. We write a wrapper class applying the Singleton pattern (here MessageResourceSingleton) that wraps an implementation of the MessageResource class
    2. Then add configuration that injects the implementation (MessageResource) into the Singleton wrapper (MessageResourceSingleton)
    The following code and configuration illustrates the Singleton injection approach:
    public class MessageResourceSingleton implements MessageResource{
    

    /** MessageResource implementation to be injected */
    private MessageResource messageResource;

    /** singleton instance */
    private static MessageResourceSingleton singleton = new MessageResourceSingleton();
    /**
    * Gets singleton
    * @return singleton
    */

    public static MessageResourceSingleton getInstance(){
    return singleton;
    }
    /**
    * Setter for the MessageResource implementation used to inject
    * the implementation
    * @param messageResource
    */

    public void setMessageResource(MessageResource messageResource) {
    this.messageResource = messageResource;
    }
    /**
    * Delegates the call to the injected implementation
    * @param args arguments
    * @return message
    */

    public String getMessage(String key) {
    return messageResource.getMessage(key);
    }
    }
    
    

    id="singleton" class="com.xebia.example.MessageResourceSingleton" factory-method="getInstance">
    name="messageResource" ref="messageResource"/>



    id="messageResource" class="com.xebia.example.MessageResourceImpl">
    name="resourceLocation" value="classpath:/bundle.properties"/>


    Any class that wants to use the MessageResource implementation simply calls:
    MessageResourceSingleton.getInstance().getMessage(“any.key”);

    By doing so, we can use all the configuration power spring provides when defining the implementation bean. The code, which uses the implementation, is not only freed of superfluous injection code and corresponding configuration but is – as the IoC principle demands –totally unaware that Spring is pulling the strings (or beans ;-) ).

    Your gains with Singleton injection

    So, when using Singleton injection these are your gains:
    • Reduced configuration and less code (inject once use everywhere)
    • Injected Singletons can be used in classes that are not part of the beanwiring chain
    • Static methods can use injected Singletons
    • Injected Singletons can serve as beanwiring starting points
    • Increased productivity (instant usage of injected code)

    Since it all seems so simple, practical and advantageous, why not use Singleton injection everywhere in you code?

    When to use Singleton injection

    The tradeoff when considering Singleton injection is simplicity versus flexibility. The constraint is that the Singleton can only wrap one specific implementation. Therefore, every class that makes use of the Singleton wrapper will have to stick with this particular implementation. You still can have several implementations available (for unittesting, mocking etc.) but at runtime only one of these can be used throughout the application.
    In other words, when you face a “one size fits all” scenario you have a case for a Singleton injection. In more detail, the following preconditions have to be present in order to make Singleton injection a useful choice:
    • A spring bean is used in various, peripheral parts of the application
    • A spring bean has the characteristics of an utility class that needs to be initialized with external resources or other parameters
    • A spring bean has to be accessible by classes that are not part of the beanwiring chain
    • It is sufficient that at runtime only one specific implementation of the spring bean is used throughout the application

    Real world cases for Singleton injection

    I have used Singleton injection on various projects. The following type of classes have proven to be an excellent candidate for Singleton injection:
    • MessageResource utility like the one used in this example
    • Logger utility that needs to perform logging to a database or queue
    • IDGenerator that gets id’s used for logging or messaging from a database
    • CodeMapper that maps technical codes to a description
    • Business Delegate, which can be used as startingpoint of the beanwiring
    • Any utility you want to use in a framework or component, which does not provide hooks to inject spring beans (in case they are still out there…)

    Conclusion

    Where applicable Singleton injection can be an elegant solution that provides significant code and configuration simplification. Additionally, it enables you to profit from “Spring injection power” outside the standard beanwiring chain. All this can be achieved with such a simple thing like Singleton injection. It enables you to do more with less – isn’t this what programming is all about?
    By Urs Peter