Posts Tagged ‘spring’

Vaadin and Spring integration through JavaConfig

March 9th, 2014 No comments

When I wrote the first version of Learning Vaadin, I hinted at how to integrate Vaadin with the Spring framework (as well as CDI). I only described the overall approach by providing a crude servlet that queried the Spring context to get the Application instance.

At the time of Learning Vaadin 7, I was eager to work on add-ons the community provided in terms of Spring integration. Unfortunately, I was sorely disappointed, as I found only few and those were lacking in one way or another. The only stuff mentioning was an article by Petter Holmström – a Vaadin team member (and voluntary fireman) describing how one should do to achieve Vaadin & Spring integration. It was much more advanced than my own rant but still not a true ready-to-be-used library.

So, when I learned that both Vaadin and Spring teams joined forces to provided a true integration library between two frameworks I love, I was overjoyed. Even better, this project was developed by none other than Petter for Vaadin and Josh Long for Pivotal. However, the project was aimed at achieving DI through auto-wiring. Since JavaConfig makes for a cleaner and more testable code, I filled an issue to allow that. Petter kindly worked on this, and in turn, I spent some time making it work.

The result of my experimentation with Spring Boot Vaadin integration has been published on, a blog exclusively dedicated to Vaadin.

Send to Kindle
Categories: JavaEE Tags: , ,

Integrate Spring JavaConfig with legacy configuration

November 9th, 2013 1 comment

The application I’m working on now uses Spring both by parsing for XML Spring configuration files in pre-determined locations and by scanning annotations-based autowiring. I’ve already stated my stance on autowiring previously, this article only concerns itself on how I could use Spring JavaConfig without migrating the whole existing codebase in a single big refactoring.

This is easily achieved by scanning the package where the JavaConfig class is located in the legacy Spring XML configuration file:

<ctx:component-scan base-package="" />

However, we may need to inject beans created through the old methods into our new JavaConfig file. In order to achieve this, we need to autowire those beans into JavaConfig:

public class JavaConfig {

    private FooDao fooDao;

    private FooService fooService;

    private BarService barService;

    public AnotherService anotherService() {

        return new AnotherService(fooDao);

    public MyFacade myFacade() {

        return new MyFacade(fooService, barService, anotherService());

You can find complete sources for this article (including tests) in IDEA/Maven format.

Thanks to Josh Long and Gildas Cuisinier for the pointers on how to achieve this.

Send to Kindle
Categories: Java Tags: ,

My case against autowiring

November 3rd, 2013 8 comments

Autowiring is a particular kind of wiring, where injecting dependencies is not explicit but actually managed implicitly by the container. This article tries to provide some relevant info regarding disadvantages of using autowiring. Although Spring is taken as an example, the same reasoning can apply to JavaEE’s CDI.

Autowiring basics

Autowiring flavors

Autowiring comes into different flavors:

  • Autowiring by type means Spring will look for available beans that match the type used in the setter. For example, for a bean having a setCar(Car car) method, Spring will look for a Car type (or one of its subtype) in the bean context.
  • Autowiring by name means Spring search strategy is based on beans name. For the previous example, Spring will look for a bean named car regardless of its type. This both requires the bean to be named (no anonymous bean here) and implies that the developer is responsible for any type mistmatch (if the car bean is of type Plane).

Autowiring is also possible for constructor injection.

Autowiring through XML configuration

Let’s first dispel some misconceptions: autowiring does not imply annotations. In fact, autowiring is available through XML since ages and can be enabled with the following syntax.

<bean autowire="byType" class="some.Clazz" />

This means Spring will try to find the right type to fill the dependency(ies) by using setter(s).

Alternative autowire parameters include:

  • by name: instead of matching by type, Spring will use bean names
  • constructor: constructor injection restricted to by-type
  • autodetect: use constructor injection, but falls back to by-type if no adequate constructor is found

Autowiring through annotations configuration

Available annotations are the following:

Annotation Description Source
 org.springframework.bean.factory.@Autowired  Wires by type  Spring 2.5+
 javax.annotation.@Resource  Wires by name  JavaEE 5+
 javax.inject.@Inject  Wires by type  JavaEE 6+
javax.inject.@Qualifier  Narrows type wiring  JavaEE 6+

Dependency Injection is all about decoupling your classes from one another to make them more testable. Autowiring through annotations strongly couples annotated classes to annotations libraries. Admittedly, this is worse for Spring’s @Autowired than for others as they are generally provided by application servers.

Why it is so bad after all?

Autowiring is all about simplifying dependency injection, and although it may seem seductive at first, it’s not maintainable in real-life projects.

Explicit dependency injection is – guess what, explicitly defining a single bean to match the required dependency. Even better, if Java Configuration is used, it is validated at compile time.

On the opposite, autowiring is about expressing constraints on all available beans in the Spring context so that one and only one matches the required dependency. In effect, you delegate wiring to Spring, tasking him to find the right bean for you. This means that by adding beans in your context, you run the risk of providing more than one match, if your previous constraints do not apply to the new beans. The larger the project, the larger the team (or even worse, the number of teams), the larger the context, the higher the risk.

For example, imagine you crafted a real nice service with a single implementation, that you need to inject somewhere. After a while, someone notices your service but creates an alternative implementation for some reason. By just declaring this new bean in the context, along with the former, it will break container initialization! Worse, it may be done in an entirely different part of the application, with seemingly no link with the former. At this point, good luck to analyze the reason of the bug.

Note that autowiring by name if even worse, since bean names have a probability of collision, even across different type hierarchies.

Autowiring is bad in Spring, but it is even worse in CDI where every class in the classpath is a candidate for injection. By the way, any CDI guru reading this post care to explain why autowiring is the only way of DI? That would be really enlightening.


In this post, I tried to explain what is autowiring. It can be used all right, but now you should be aware of its con. IMHO, you should only use it for prototyping or quick-and-dirty proof of concepts, everything that can be discarded after a single use. If really needed, prefer wiring by type over wiring by name as at least it matching doesn’t depend on a String.

Send to Kindle
Categories: Java Tags: , ,

Spring method injection with Java Configuration

October 27th, 2013 No comments

Last week, I described how a Rich Model Object could be used with Spring using Spring’s method injection from an architectural point of view.

What is missing, however, is how to use method injection with my new preferred method for configuration, Java Config. My start point is the following, using both autowiring (<shudder>) and method injection.

public abstract class TopCaller {

    private StuffService stuffService;

    public SomeBean newSomeBean() {

        return newSomeBeanBuilder().with(stuffService).build();

    public abstract SomeBeanBuilder newSomeBeanBuilder();

Migrating to Java Config requires the following steps:

  1. Updating the caller structure to allow for constructor injection
  2. For method injection, provide an implementation for the abstract method in the configuration class
  3. That’s all…
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

public class JavaConfig {

    public TopCaller topCaller() {

        return new TopCaller(stuffService()) {

            public SomeBeanBuilder newSomeBeanBuilder() {

                return someBeanBuilder();

    public StuffService stuffService() {

        return new StuffService();

    public SomeBeanBuilder someBeanBuilder() {

        return new SomeBeanBuilder();
Send to Kindle
Categories: Java Tags: , ,

Rich Domain Objects and Spring Dependency Injection are compatible

October 20th, 2013 3 comments

I’m currently working in a an environment where most developers are Object-Oriented fanatics. Given that we develop in Java, I think that it is a good thing – save the fanatics part. In particular, I’ve run across a deeply-entrenched meme that states that modeling Rich Domain Objects and using Spring dependency injection at the same time is not possible. Not only is this completely false, it reveals a lack of knowledge of Spring features, one I’ll be trying to correct in this article.

However, my main point is not about Spring but about whatever paradigm one holds most dear, be it Object-Oriented Programming, Functional Programming, Aspect-Oriented Programming or whatever. Those are only meant to give desired properties to software: unit-testable, readable, whatever… So one should always focus on those properties than on the way of getting them. Remember:

When the wise man points at the moon, the idiot looks at the finger.

Back to the problem at hand. The basic idea is to have some bean having reference on some service to do some stuff (notice the real-word notions behind this idea…) so you could call:


The following is exactly what not to do:

public class TopCaller {

    private StuffService stuffService;

    public SomeBean newSomeBean() {

        return new SomeBeanBuilder().with(stuffService).build();

This design should be anathema to developers promoting unit-testing as the new() deeply couples the TopCaller and SomeBeanBuilder classes. There’s no way to stub this dependency in a test, it prevents testing the createSomeBean() method in isolation.

What you need is to inject SomeBean prototypes into the SomeBeanBuilder singleton. This is method injection and is possible within Spring with the help of lookup methods (I’ve already blogged about that some time ago and you should probably have a look at it).

public abstract class TopCaller {

    private StuffService stuffService;

    public SomeBean newSomeBean() {

        return newSomeBeanBuilder().with(stuffService).build();

    public abstract SomeBeanBuilder newSomeBeanBuilder();

With the right configuration, Spring will take care of providing a different SomeBeanBuilder each time the newSomeBeanBuilder() method is called. With this new design, we changed the strong coupling between TopCaller and SomeBeanBuilder to a soft coupling, one that can be stubbed in tests and allow for unit-testing.

In the current design, it seems the only reason for SomeBeanBuilder to exist is to pass the StuffService from the TopCaller to SomeBean instances. There is no need to keep it with method injection.

There are two different possible improvements:

  1. Given our “newfound” knowledge, inject:
    • method newSomeBean() instead of newSomeBeanBuilder() into TopCaller
    • StuffService directly into SomeBean

  2. Keep StuffService as a TopCaller attribute and pass it every time doStuff() is invoked

I would favor the second option since I frown upon a Domain Object keeping references to singleton services, unless there are many parameters to pass at every call. As always, there’s not a single best choice, but only contextual choices.

Also, I would also use explicit dependency management instead of some automagic stuff, but that another debate.

I hope this piece proved beyond any doubt that Spring does not prevent Rich Domain Model, far from it. As a general rule, know about tools you use and go their way instead of following some path just for the sake of it .

Send to Kindle

Spring 3.2 sweetness

June 23rd, 2013 No comments

Even the most extreme Spring opponents have to admit it is all about making developers life easier. Version 3.2 of Spring MVC brings even more sweetness to the table.

Sweetness #1: No web.xml

The ability to run a webapp without any web deployment descriptor comes from Servlet 3.0.

One option would be to annotate your servlet with the @WebServlet annotation to set mapping and complementary data. When you get your servlet for free, like Spring’s DispatcherServlet, you’d need to subclass you servlet for no other purpose than adding annotation(s).

Alternatively, Servlet 3.0 offers a way to both programmatically register servlets in the container and to offer hooks at startup through the ServletContainerInitializer interface. The container will call the onStartup() method of all concrete implementation at webapp startup. The Spring framework leverages this feature to do so for WebApplicationInitializer instances.

Spring MVC 3.2 provides such an implementation – AbstractContextLoaderInitializer, to programmatically register the DispatcherServlet. This means that as soon as the spring-webmvc jar is in the WEB-INF/lib folder of the webapp, you’ve got the Dispatcher servlet up and ready.

This replaces both the servlet and servlet mapping and the context listener declarations in the web.xml.

Sweetness #2: Easy Java configuration integration

Java configuration is the way to configure Spring injection explicitly in a typesafe way. I won’t go into the full demonstration of it, as I already wrote about that some time ago.

Earlier Spring versions provided a way to use Java configuration classes instead of XML files in the web deployment descriptor. Spring 3.2 offers AbstractAnnotationConfigDispatcherServletInitializer, a AbstractContextLoaderInitializer subclass with hooks for Java configuration classes.

Your own concrete subclass has to implement methods to define servlet mappings, as well as root and web Java configuration classes:

public class SugarSpringWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    protected Class<?>[] getRootConfigClasses() {

        return new Class[] { JavaConfig.class };

    protected Class<?>[] getServletConfigClasses() {

        return new Class[] { WebConfig.class };

    protected String[] getServletMappings() {

        return new String[] { "/" };

At this point, you just need to create those configuration classes.

Sweetness #3: integration testing at the mapping level

Your code should be unit-tested, that is tested in isolation to ensure that each method is bug-free, and integration-tested to ensure that collaboration between classes yield expected results.

Before v. 3.2, the Spring test framework let you assemble your configuration classes / files easily enough. The problem lay in the way you would call entry-points – the controllers. You could call methods of those controllers, but not the mappings, leaving those untested.

With v. 3.2, Spring Test brings a whole MVC testing framework which entry-points are mappings. This way, instead of testing method x() of controller C, you would test a request to /z, letting Spring MVC handle it so we can check for expected results.

The framework also provide expectations for view returning, forwarding, redirecting, and model attribute setting, all with the help of a specific DSL:

public class SayHelloControllerIT extends AbstractTestNGSpringContextTests {

    private MockMvc mockMvc;

    public void setUp() {

        mockMvc = webAppContextSetup((WebApplicationContext) applicationContext).build();

    @Test(dataProvider = "pathParameterAndExpectedModelValue")
    public void accessingSayhelloWithSubpathShouldForwardToSayHelloJspWithModelFilled(String path, String value) throws Exception {

        mockMvc.perform(get("/sayHello/Jo")).andExpect(view().name("sayHello")).andExpect(model().attribute("name", "Jo"));

The project for this article can be downloaded in Eclipse/Maven format.

To go further:

  • The entire set of new features is available here
Send to Kindle

Modularity in Spring configuration

June 2nd, 2013 1 comment

The following goes into more detail what I already ranted about in one of my previous post.

In legacy Spring applications I’ve to develop new features in, I regularly stumble upon a big hindrance that slows down my integration-testing effort. This hindrance, and I’ll go as far as naming it an anti-pattern, is to put every bean in the same configuration file (either in XML or in Java).

The right approach is to define at least the following beans in a dedicated configuration component:

  • Datasource(s)
  • Mail server
  • External web services
  • Every application dependency that doesn’t fall into one of the previous category

Depending on the particular context, we should provide alternate beans in test configuration fragments. Those alternatives can either be mocked beans or test doubles. In the first case, I would suggest using the Springockito framework, based upon Mockito; in the second case, tools depend on the specific resource: in-memory database (such as HSQLDB, Derby or H2*) for datasource and GreenMail for mail server.

It is up to the application and each test’s responsibility to assemble the different required configuration fragments to initialize the full-fledged Spring application context. Note that coupling fragments together is also not a good idea.

* My personal preference goes to H2 these days

Send to Kindle
Categories: Java Tags:

Devoxx France 2013 – Day 3

March 30th, 2013 1 comment

Classpath isn’t dead… yet by Alexis Hassler

Classpath is dead!
Mark Reinold

What is the classpath anyway? In any code, there are basically two kinds of classes: those coming from the JRE, and those that do not (either becasue they are your own custom class or becasue they come from 3rd-party libraries). Classpath can be set either with a simple java class load by the -cp argument or with a JAR by the embedded MANIFEST.MF.

A classloader is a class itself. It can load resources and classes. Each class knows its classloader, that is which classloader has loaded the class inside the JVM (i.e. sun.misc.Launcher$AppClassLoader). JRE classes classloader is not not a Java type, so the returned classloader is null. Classloader are organized into a parent-child hierarchy, with delegation from bottom to top if a class is not found in the current classloader.

The BootstrapClassLoader can be respectively replaced, appended or prepended with -Xbootclasspath,-Xbootclasspath/a and -Xbootclasspath/p. This is a great way to override standard classes (such as String or Integer); this is also a major security hole. Use at your own risk! Endorsed dir is a way to override some API with a more recent version. This is the case with JAXB for example.

ClassCastException usually comes from the same class being loaded by two different classloaders (or more…). This is because classes are not identified inside the JVM by the class only, but by the tuple {classloader, class}.

Classloader can be developed, and then set in the provided hierarchy. This is generally done in application servers or tools such as JRebel. In Tomcat, each webapp has a classloader, and there’s a parent unified classloader for Tomcat (that has the System classloader as its parent). Nothing prevents you from developing your own: for example, consider a MavenRepositoryClassLoader, that loads JAR from your local Maven repository. You just have to extends UrlClassLoader.

JAR hell comes from dependencies management or more precisely its lack thereof. Since dependencies are tree-like during development time, but completely flat at runtime i.e. on the classpath, conflicts may occur if no care is taken to eliminate them beforehand.

One of the problem is JAR visibility: you either have all classes available if the JAR is present, or none if it is not. The granularity is at the JAR level, whereas it would be better to have finer-grained visibility. Several solutions are available:

  • OSGi has an answer to these problems since 1999. With OSGi, JARs become bundles, with additional meta-data set in the JAR manifest. These meta-data describe visibility per package. For a pure dependency management point of view, OSGi comes with additional features (services and lifecycle) that seem overkill [I personally do not agree].
  • Project Jigsaw also provides this modularity (as well as JRE classes modularity) in the form of modules. Unfortunately, it has been delayed since Java 7, and will not be included in Java 8. Better forget it at the moment.
  • JBoss Module is a JBoss AS 7 subproject, inspired by Jigsaw and based on JBoss OSGi. It is already available and comes with much lower complexity than OSGi. Configuration is made through a module.xml description file. This system is included in JBoss AS 7. On the negative side, you can use Module either with JBoss or on its own, which prevents us from using it in Tomcat. An ongoing Github proof-of-concept achieves it though, which embeds the JAR module in the deployed webapp and overrides Tomcat classloader of the webapp.
    Several problems still exists:

    • Artefacts are not modules
    • Lack of documentation

Animate your HTML5 pages with CSS3, SVG, Canvas & WebGL by Martin Gorner

Within the HTML5 specification alone, there are 4 ways to add fun animations to your pages.

CSS 3 transitions come through the transition property. They are triggered though user-events.Animations are achieved through animation properties. Notice the plural, because you define keyframes and the browser computes intermediate ones.2D transformations -property transformation include rotate, scale, skew, translate and matrix. As an advice, timing can be overriden, but the default one is quite good. CSS 3 also provides 3D transformations. Those are the same as above, but with either X, Y or Z appended to the value name to specify the axis name.The biggest flaw from CSS 3 is that they lack draw features.
SVG not only provides vectorial drawing features but also out-of-the-box animation features. SVG is described in XML: SVG animations are much more powerful that CSS 3 but also more complex. You’d better use a tool to generate it, such as Inkscape.There are different ways to animate SVG, all through sub-tags: animate, animateTransform and animateTransform.Whereas CSS 3 timing is acceptable out-of-the-box, default in SVG is linear (which is not pleasant to the eye). SVG offers timing configuration through the keySplines attribute of the previous tags.Both CSS 3 and SVG have a big limitations: animations are set in stone and cannot respond to external events, such as user inputs. When those are a requirement, the following two standard apply.
Canvas + JavaScript
From this point on, programmatic (as opposed to descriptive) configuration is available. Beware that JavaScript animations comes at a cost: on mobile devices, it will dry power. As such, know about method that let the browser stop animations when the page is not displayed.
WebGL + THREE.js
WebGL let use a OpenGL API (read 3D), but it is very low-level. THREE.js comes with a full-blown high level API. Better yet, you can import Sketchup mesh models into THREE.js.In all cases, do not forget to use the same optimization as in 2D canvas to stop animations when the canvas is not visible.

Tip: in order to not care about prefix, prefix.js let us preserve original CSS and enhance with prefix at runtime. Otherwise, use LESS / SASS. Slides are readily available online with associated labs.
[I remember using the same 3D techniques 15 years ago when I learnt raytracing. That's awesome!]

The Spring update by Josh Long

[Talk is shown in code snippets, rendering full-blown notes mostly moot. It is dedicated to new features of the latest Spring platform versions]

Version Feature
  • JavaConfig equivalents of XML
  • Profiles
  • Cache abstraction, with CacheManager and Cache
  • Newer backend cache adapters (Hazelcast, memcached, GemFire, etc.) in addition to EhCache
  • Servlet 3.0 support
  • Spring framework code available on GitHub
  • Gradle-based builds [Because of incompatible versions support. IMHO, this is one of the few use-case for using Gradle that I can agree with]
  • Async MVC processing through Callable (threads are managed by Spring), DeferredResult and AsyncTask<?>
  • Content negotiation strategies
  • MVC Test framework server
  • Groovy-configuration support. Note that all available configuration ways (XML, JavaConfig, etc.) and their combinations have no impact at runtime
  • Java 8 closures support
  • JSR 310 (Date and Time API) support
  • Removal of setting @PathVariable‘s value need, using built-in JVM mechanism to get it
  • Various support for Java EE 7
  • Backward compatibility will still include Java 5
  • Annotation-based JMS endpoints
  • WebSocket aka “server push” support
  • Web resources caching

Bean validation 1.1: we’re not in Care Bears land anymore by Emmanuel Bernard

All that will be written here is not set in stone, it has to be approved first. Bean Validation comes bundled with Java EE 6+ but it can be used standalone.

Before Bean Validation, validations were executed at each different layer (client, application layers, database). This led to duplications as well as inconsistencies. The Bean Validation motto is something along the lines of:

Constrain once, run anywhere

1.0 has been released with Java EE 6. It is fully integrated with other stacks including JPA, JSF (& GWT, Wicket, Tapestry) and CDI (& Spring).

Declaring a constraint is as simple as adding a specific validation annotation. Validation can be cascaded, not only on the bean itself but on embedded beans. Also, validation may wrap more than one property to validate if two different properties are consistent with one another. Validation can be set on the whole, but also defined subsets – called groups, of it. Groups are created through interfaces.

Many annotations come out-of-the-box, but you can also define your own. This is achieved with the @Constraint annotation on a custom annotation. It includes the list of validators to use when validating. Those validators must implement the Validator interface.

1.1 will be included in Java EE 7. The most important thing to remember is that it is 100% open. Everything is available on GitHub, go fork it.

Now, containers are in complete control of Bean Validation components creation, so that they are natively compatible with CDI. Also, other DI containers, such as Spring, may plug in their own SPI implementation.

The greatest feature of 1.1 is that not only properties can be validated, but also method parameters and method return values. Constructors being specialized method, it also applies to them. It is achieved internally with interceptors. However, this requires an interception stack – either CDI, Spring or any AOP, and comes with associated limitations, such as proxies. This enables declarative Contract-Oriented Programming, and its pre- and post-conditions.


Devoxx France 2013 has been a huge success, thanks to the organization team. Devoxx is not only tech talks, it is also a time to meet new people, exchange ideas and see old friends.

See you next year, or at Devoxx 2013!

Thanks to my employer – hybris, who helped me attend this great event!

Send to Kindle
Categories: Event Tags: , , ,

Consider replacing Spring XML configuration with JavaConfig

March 10th, 2013 5 comments

Spring articles are becoming a trend on this blog, I should probably apply for a SpringSource position :-)

Colleagues of mine sometimes curse me for my stubbornness in using XML configuration for Spring. Yes, it seems so 2000′s but XML has definite advantages:

  1. Configuration is centralized, it’s not scattered among all different components so you can have a nice overview of beans and their wirings in a single place
  2. If you need to split your files, no problem, Spring let you do that. It then reassembles them at runtime through internal <import> tags or external context files aggregation
  3. Only XML configuration allows for explicit wiring – as opposed to autowiring. Sometimes, the latter is a bit too magical for my own taste. Its apparent simplicity hides real complexity: not only do we need to switch between by-type and by-name autowiring, but more importantly, the strategy for choosing the relevant bean among all eligible ones escapes but the more seasoned Spring developers. Profiles seem to make this easier, but is relatively new and is known to few
  4. Last but not least, XML is completely orthogonal to the Java file: there’s no coupling between the 2 so that the class can be used in more than one context with different configurations

The sole problem with XML is that you have to wait until runtime to discover typos in a bean or some other stupid boo-boo. On the other side, using Spring IDE plugin (or the integrated Spring Tools Suite) definitely can help you there.

An interesting alternative to both XML and direct annotations on bean classes is JavaConfig, a former separate project embedded into Spring itself since v3.0. It merges XML decoupling advantage with Java compile-time checks. JavaConfig can be seen as the XML file equivalent, only written in Java. The whole documentation is of course available online, but this article will just let you kickstart using JavaConfig. As an example, let us migrate from the following XML file to a JavaConfig

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <bean id="button" class="javax.swing.JButton">
        <constructor-arg value="Hello World" />

    <bean id="anotherButton" class="javax.swing.JButton">
        <property name="icon" ref="icon" />

    <bean id="icon" class="javax.swing.ImageIcon">
            <bean class="">
            	<constructor-arg value="" />

The equivalent file is the following:


import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class MigratedConfiguration {

    public JButton button() {

        return new JButton("Hello World");

    public JButton anotherButton(Icon icon) {

        return new JButton(icon);

    public Icon icon() throws MalformedURLException {

        URL url = new URL("");

        return new ImageIcon(url);

Usage is simpler than simple: annotate the main class with @Configuration and individual producer methods with @Bean. The only drawback, IMHO, is that it uses autowiring. Apart from that, It just works.

Note that in a Web environment, the web deployment descriptor should be updated with the following lines:


Sources for this article are available in Maven/Eclipse format here.

To go further:

  • Java-based container configuration documentation
  • AnnotationConfigWebApplicationContext JavaDoc
  • @ContextConfiguration JavaDoc (to configure Spring Test to use JavaConfig)
Send to Kindle
Categories: Java Tags: ,

Spring beans overwriting strategy

February 16th, 2013 2 comments

I find myself working more and more with Spring these days, and what I find raises questions. This week, my thoughts are turned toward beans overwriting, that is registering more than one bean with the samee name.

In the case of a simple project, there’s no need for this; but when building a a plugin architecture around a core, it may be a solution. Here are some facts I uncovered and verified regarding beans overwriting.

Single bean id per file
The id attribute in the Spring bean file is of type ID, meaning you can have only a single bean with a specific ID in a specific Spring beans definition file.
Overwriting bean dependent on context fragments loading order
As opposed to classpath loading where the first class takes priority over those others further on the classpath, it’s the last bean of the same name that is finally used. That’s why I called it overwriting. Reversing the fragment loading order proves that.
Fragment assembling methods define an order
Fragments can be assembled from <import> statements in the Spring beans definition file or through an external component (e.g. the Spring context listener in a web app or test classes). All define a deterministic order.
As a side note, though I formerly used import statements in my projects (in part to take advantage of IDE support), experience taught me it can bite you in the back when reusing modules: I’m in favor of assembling through external components now.
Spring lets you define names in addition to ids (which is a cheap way of putting illegals characters fors ID). Those names also overwrites ids.
Spring lets you define aliases of existing beans: those aliases also overwrites ids.
Scope overwriting
This one is really mean: by overwriting a bean, you also overwrite scope. So, if the original bean had a specified scope and you do not specify the same, tough luck: you just probably changed the application behavior.

Not only are perhaps not known by your development team, but the last one is the killer reason not to overwrite beans. It’s too easy to forget scoping the overwritten bean.

In order to address plugins architecture, and given you do not want to walk the OSGi path, I would suggest what I consider a KISS (yet elegant) solution.

Let us use simple Java properties in conjunction with ProperyPlaceholderConfigurer. The main Spring Beans definition file should define placeholders for beans that can be overwritten and read two defined properties file: one wrapped inside the core JAR and the other on a predefined path (eventually set by a JVM property).

Both property files have the same structure: fully-qualified interface names as keys and fully-qualified implementations names as values. This way, you define default implementations in the internal property file and let uses overwrite them in the external file (if necessary).

As an added advantage, it shields users from Spring so they are not tied to the framework.

Sources for this article can be found in Maven/Eclipse format here.

Send to Kindle
Categories: Java Tags: