» tagged pages
» logout

sorted by: recent | see : popular
Content Tagged with Container + Spring

The Common Service Locator library

The CommonServiceLocator project was released this week on CodePlex with the general idea of providing an IoC container agnostic API for resolving dependencies using Service Location. Erich Eichinger from SpringSource contributed the Spring.NET implementation, thanks Erich! Here is the API so you get the basic idea public interface IServiceLocator : System.IServiceProvider {   object GetInstance(Type [...]

Spring: Interface21 Team Blog

The Common Service Locator library

The CommonServiceLocator project was released this week on CodePlex with the general idea of providing an IoC container agnostic API for resolving dependencies using Service Location. Erich Eichinger from SpringSource contributed the Spring.NET implementation, thanks Erich! Here is the API so you get the basic idea public interface IServiceLocator : System.IServiceProvider {   object GetInstance(Type [...]

Spring: Ben Hale's Blog

Springframework.org

Welcome to the home of the Spring Framework, the leading full-stack Java/JEE application framework.

Spring: del.icio.us/tag/SpringFramework

Spring Java Configuration - What's New in M3

Chris Beams

Today marks the third milestone release of the Spring Java Configuration project (JavaConfig for short). The release contains numerous bug fixes and new features - I'll highlight a few of the most interesting changes below, but first let me give a quick refresher as to what JavaConfig is all about.

If you have any experience with Spring, the following snippet of XML configuration will likely be familiar. Let's assume we're looking at a file named application-config.xml:

<beans>
        <bean id="orderService" class="com.acme.OrderService"/>
                <constructor-arg ref="orderRepository"/>
        </bean>
        <bean id="orderRepository" class="com.acme.OrderRepository"/>
                <constructor-arg ref="dataSource"/>
        </bean>
</beans>

Of course, this XML configuration will ultimately serve as a set of instructions for a Spring ApplicationContext to instantiate and configure our beans:

ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");
OrderService orderService = (OrderService) ctx.getBean("orderService");

JavaConfig simply provides another mechanism to configure the Spring IoC container, this time in pure Java rather than requiring XML to get the job done. Let's port the configuration above to JavaConfig:

@Configuration
public class ApplicationConfig {
        public @Bean OrderService orderService() {
                return new OrderService(orderRepository());
        }

        public @Bean OrderRepository orderRepository() {
                return new OrderRepository(dataSource());
        }

        public @Bean DataSource dataSource() {
                // instantiate and return an new DataSource …
        }
}

Like the original XML file, this class is simply a set of instructions as to how to construct our application's various components. We'll supply these instructions to an ApplicationContext implementation specifically designed to read and execute Java-based configuration instructions:

JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class);
OrderService orderService = ctx.getBean(OrderService.class);

And that's it! Well, almost. Of course there's a lot more to JavaConfig, but for the most part the feature set is 1:1 with what's available in Spring's XML config. For full details on how to use JavaConfig, take a look at the reference documentation. If you're new to JavaConfig, be sure to check out the quick start section.

At any rate, the benefits of JavaConfig are straightforward:

  • It's pure Java, so there's no XML required
  • You get all the benefits of object-orientation in your configuration code
  • It's type-safe and refactoring-friendly
  • You still get the full power of the core Spring IoC container

With that in mind, let's take a look at what's changed in the M3 release:

AnnotationApplicationContext deprecated

Hardly a 'new feature', but this change is important to mention because much of what I'll discuss below revolves around JavaConfigApplicationContext, the successor to AnnotationApplicationContext. Why was this change made? AnnotationApplicationContext posed a significant naming collision with Spring 2.5's Annotation-Driven Injection facility. JavaConfig presents a different approach to configuration than Annotation-Driven Injection, so we wanted to make this distinction clear by renaming the class entirely. AnnotationApplicationContext will remain deprecated until the 1.0.0.rc1 release, at which point it will be removed permanently.

Type-safety improvements

While the above-mentioned JavaConfigApplicationContext behaves largely like it's predecessor, it also introduces type-safe getBean() methods that take full advantage of generics. The following code now works (and from this point forward is the preferred approach to use with JavaConfig):

JavaConfigApplicationContext context = new JavaConfigApplicationContext(AppConfig.class);
OrderService orderService = context.getBean(OrderService.class);

Look ma, no casting! And no string-based lookups, either. Of course, this will beg the question, "what if two or more objects of type OrderService have been configured in the context?" This is a situtation that could easily occur, and there are multiple ways to address it. For brevity in this post, I'll simply refer those interested to take a look at the disambiguation options section of the reference documentation.

These type-safe getBean() methods have also been fitted onto the ConfigurationSupport base class, such that the following is possible:

@Configuration
public class ApplicationConfig extends ConfigurationSupport {
        public @Bean OrderRepository orderRepository() {
                return new JdbcOrderRepository(this.getBean(DataSource.class));
        }
}
Major documentation update

We've worked hard to bring JavaConfig's documentation up to par with the quality for which Spring is famous. As linked above, the reference documentation is available in HTML as well as PDF formats. Note that this documentation is also packaged as part of the regular zip distributions available via SourceForge. As with all the additions in M3, your feedback on the documentation will help improve it as the project moves forward to its 1.0 GA release.

Support for JavaConfig in the web tier

Prior to this release, JavaConfig had to be 'bootstrapped' via XML in order to be used in conjunction with Spring's ContextLoaderListener and DispatcherServlet classes. To address this limitation, JavaConfigWebApplicationContext has been added. Simply specify this class as the contextClass parameter in your web.xml, and you can use your @Configuration classes directly:

<web-app>
    <!– Configure ContextLoaderListener to use JavaConfigWebApplicationContext
         instead of the default XmlWebApplicationContext –>

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.config.java.context.JavaConfigWebApplicationContext</param-value>
    </context-param>
    <!– Configuration locations must consist of one or more comma- or space-delimited
         fully-qualified @Configuration classes –>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>example.RootApplicationConfig</param-value>
    </context-param>
    <!– Bootstrap the root application context as usual using ContextLoaderListener –>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!– Declare a Spring MVC DispatcherServlet as usual –>
    <servlet>
        <servlet-name>dispatcher-servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!– Configure DispatcherServlet to use JavaConfigWebApplicationContext
             instead of the default XmlWebApplicationContext –>

        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.config.java.context.JavaConfigWebApplicationContext</param-value>
        </init-param>
        <!– Again, config locations must consist of one or more comma- or space-delimited
             and fully-qualified @Configuration classes –>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>example.web.WebBeansConfig</param-value>
        </init-param>
    </servlet>
</web-app>

In practice, it is likely that many folks will want to continue using a combination of XML and JavaConfig, especially in web applications. This approach still works just fine (see combining configuration approaches), but it was important to the team that we offer users a truly "XML-free" approach if they so desire it. This change rounds out that possibility.

Modularity improvements with new @Import annotation

Much like Spring XML config's <import/> element, it is now possible to have one @Configuration class import another (and thus all its bean definitions):

@Configuration
public class FooConfig {
        public @Bean Foo foo() {}
        public @Bean Bar bar() {}
}

@Import(FooConfig.class)
@Configuration
public class ApplicationConfig {
        public @Bean ServiceA serviceA() {}
}

JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class);
// foo, bar, and serviceA beans will all be available
ctx.getBean(ServiceA.class); // works
ctx.getBean(Foo.class); // works too
 

This functionality simply provides another tool for effectively modularizing @Configuration classes.

Externalizing values with @ExternalValue and @ResourceBundles

Several have suggested introducing functionality in JavaConfig equivalent to that of PropertyPlaceholderConfigurer for the purpose of accessing values in properties files during configuration. M3 provides just that. Let's assume we have a typical DataSource that needs its JDBC url, username and password. As per usual, these values are stored in a properties file. For the example below, that properties file will be available in our classpath at com/acme/datasource.properties. Contents of that file are as follows:

datasource.url=jdbc:localhost:…
datasource.username=scott
datasource.password=tiger

Using @ResourceBundles and @ExternalValue, we can now access these properties from within JavaConfig:

@Configuration
@ResourceBundles("classpath:/com/acme/datasource")
public abstract class ApplicationConfig {
        public @Bean OrderService orderService() {
                return new OrderServiceImpl(orderRepository());
        }

        public @Bean OrderRepository orderRepository() {
                return new JdbcOrderRepository(dataSource());
        }

        public @Bean DataSource dataSource() {
                return new DriverManagerDataSource(url(), username(), password());
        }

        abstract @ExternalValue("datasource.url") String url();
        abstract @ExternalValue("datasource.username") String username();
        abstract @ExternalValue("datasource.password") String password();
}

A couple of things to note here: see how the value of the @ResourceBundles annotation doesn't end in .properties? This is because JavaConfig is using Spring's internationalization infrastructure underneath, and will look for variations on datasource.properties such as datasource_en.properties according to the current locale. Also, while this example supplied string values to the @ExternalValue annotation, the default is to look up properties based on the method name. So, if we hadn't supplied @ExternalValue("datasource.url") String url(), and rather just @ExternalValue String url(), JavaConfig would have looked for a property named 'url'.

What's next?

A number of users have been asking when we'll see a 1.0 release of JavaConfig, and with good reason - it's been a long time coming! There remain a number of important changes, both regarding internals as well as the public API that must be addressed before we're ready to call this 'production quality' software. Expect to see more frequent milestones and release candidates in the coming weeks. Bottom line: JavaConfig is now and will continue to be fully supported going forward. If you'd like to keep an eye on progress, please visit JavaConfig's JIRA issue tracking, especially the road map view.

Feedback Requested!

If you've made it this far through the post it's a safe bet you're at least interested in JavaConfig ) So take the next step! Download the release, read the documentation, give it a spin and let us know what you think.

[Update 3/27: Post was accidentally deleted, and so re-posted - apologies to those who had already written comments, as they were deleted in the process.]
[Update 4/4: fixed a typo in the sample web.xml.]

Spring: Interface21 Team Blog

Spring Dependency Injection & Java 5 (including slides and code)

Alef Arendsen

I'm writing this as I'm on my way to Cairo. We're flying just West of Italy and I have clear view on the Italian coast line, with its blue waters and waves gently moving towards shore. It must be nice down there now. I'm heading to Cairo for a meeting of the Egyptian User Group, organized by Ahmed Hashim, who no doubt will have done an excellent job, I'm sure of that. I'll be presenting on Spring with the theme this time being Dependency Injection, type safety and Java 5. Yesterday (March 14th that is), I did almost the same presentation at the Profict Wintercamp in Loenen, NL for an audience of 60 of 70 I think.

Lately there has been a lot of talk about type safety, Spring and other dependency injection approaches. Way too often, I found people referring to Spring as having dependency injection features that are not type safe and even worse, people that were referring to Spring as having a dependency on XML . As I can't keep looking out the airplane window for ever (well, I probably can, but it's not that useful), I figured I'd write a little blog entry on the current status of dependency injection with Spring and Java 5.

With the addition of features in Spring 2.5 and also with Spring's sub project JavaConfig the type safety argument and the argument that Spring is tied to XML is simply not true anymore. While in the past, we've always said that Spring was not coupled to XML, surely the only viable option of expression your configuration details was XML. But since Spring 2.5, this is no longer a theoretical argument; there is a practicably usable option for configuring your dependencies using plain Java.

Spring @Autowired support

Spring 2.5 itself provides annotation-based dependency injection, where hints are giving to the Spring container where to inject dependencies using @Autowired annotations and @Qualifier annotations (or any other custom annotation for that matter). I will not cover the entire mechanism here. Instead, I'll highlight the blog entries and articles that cover the @Autowired approach:

  • Introducing the Spring Framework 2.5 by Rod Johnson
  • Spring 2.5's Comprehensive Annotation Support by Juergen Hoeller
  • Customizing Annotation Configuration and Component Detection in Spring 2.5 by Mark Fisher
  • Spring JavaConfig

    In addition to the @Autowired support, Spring JavaConfig provides a entirely new approach to dependency injection. Plenty of blog entries have been talking about JavaConfig already, so I won't fully explain it here again. I got several questions recently about the status of JavaConfig. We haven't published any milestones for this project in a while. This certainly not without reason. Although the model already works quite well, we are still not done fleshing out some of the details. We want to release something we're 100% happy with and right now, it's simply not
    done yet. Keep an eye on the JavaConfig project page and this blog. A new milestone release is just around the corner.

    The JavaConfig approach is highlighted in more detail in various blog entries as well:

    As I've also said in the sessions in Loenen and in Cairo, Spring JavaConfig is not yet done. There are still a few details to be fleshed to create a smooth DI language that supports all the features that the XML-based DI language also has. This is where (if you like) you can help us a lot. Try Spring JavaConfig and tell us what you think!

    Conclusion

    One other quite important point I tried to get across in my presentation yesterday and that's the idea of the Spring container as a dependency injection platform, with various DI flavors implemented on top of it. The first flavor, has existed for 5 years already (the XML-based approach). The second has also been around for quite a while already and now provides the basis for the EJB3 SessionBean functionality inside BEA WebLogic version 10 (and is also available in the public domain under the name Pitchfork). The last flavor that we released is the @Autowired flavor and next up is JavaConfig. Having the platform is what counts for us. It'll help us get you an nice experience with full backwards-compatibility, whether you're using
    JavaConfig, @Autowired or our XML-based approach (or, all at the same time for that matter).

    A word on the source code and slides

    In the slides you will see I've included an image of a Ford Model T. The analogy that I always use when describing Dependency Injection is a car assembly line. Without the car assembly line (according to Wikipedia), Ford could produce 11 Model Ts per month. With the assembly line one Model T took only 93 minutes. A standardized process of assembling parts (that do not know how they are going to be assembled) into a working car is very beneficial. In my opinion, having an approach that does not touch your main-line logic is important. JavaConfig offers this.

    The code is attached as well. There is a dependency on the JTA API (the demo uses Hibernate), which is not installed in the Maven Repository. Lucio Benfante has blogged about solving this problem (installing the JTA API in your local repository).

    After you've installed the JTA API, run the CarPlantIntegrationTests in the com.carplant.plant package and read the comment for the class. This explains how to enable JavaConfig, Autowire config and the XML config (JavaConfig has been enabled by default).

    [update] added one more resource on JavaConfig

Spring: Interface21 Team Blog

Spring 2.5's Comprehensive Annotation Support

Juergen Hoeller

One of the central themes behind Spring 2.5 is comprehensive annotation-based configuration. We've been talking and blogging a lot about @Autowired, about Spring MVC's @RequestMapping and also about the new support for annotated tests written with JUnit4 or TestNG. @Autowired is certainly the central one of Spring 2.5's annotations, being available for use in service components, web components, unit tests - even domain objects when using Spring's @Configurable with AspectJ weaving. Spring MVC's @RequestMapping is equally flexible, supporting many variants of handler method signatures.

Today I'd like to take a different focus, namely on the wide-ranging set of dependency injection annotations supported by Spring. The following list includes the key annotations that can be used within Spring 2.5 beans:

  • org.springframework.beans.factory.annotation.Required:
    Identifies bean property setters that must be called (as opposed to optional setters). Supported since Spring 2.0.
  • org.springframework.beans.factory.annotation.Autowired:
    Spring 2.5's central injection annotation, applying to constructors, config methods and fields. Performs injection of components by type, with supporting for "qualifier" annotations that narrow the potential set of candidates in case of multiple matches.
  • javax.annotation.PostConstruct:
    JSR-250's common annotation for what Spring calls "init methods".
  • javax.annotation.PreDestroy:
    JSR-250's common annotation for what Spring calls "destroy methods".
  • javax.annotation.Resource:
    JSR-250's common annotation for injecting an external component by name. A "resource" in JSR-250 terminology really refers to a middleware component such as a DataSource.
  • javax.xml.ws.WebServiceRef:
    @Resource-like, for JAX-WS service lookups, injecting a JAX-WS port proxy.
  • javax.ejb.EJB:
    @Resource-like, for EJB Session Bean lookups, injecting an EJB component reference.
  • javax.persistence.PersistenceUnit:
    injecting a JPA EntityManagerFactory by persistence unit name. Supported since Spring 2.0.
  • javax.persistence.PersistenceContext:
    injecting a JPA EntityManager by persistence unit name. Supported since Spring 2.0.


This set of annotations encompasses all of Java EE 5's common annotations, which means that you may use the same common annotations in e.g. Servlet 2.5 servlets, JSF 1.2 managed beans and Spring managed beans. In other words, if you have some standard JSF 1.2 managed beans with annotation usage, you can take them as-is and move their definitions from faces-config to a Spring application context, without any change in the bean classes! This was an important design goal: Spring 2.5 may serve as straightforward replacement of the standard JSF 1.2 managed bean facility, simply through choosing SpringBeanFacesELResolver as your custom JSF ELResolver.

Configuration-wise, all you need to enable the complete set of annotations above is the following simple configuration element in your Spring application context:

<context:annotation-config/>

Note that this setting is related to dependency injection only and does not require any parameterization. (For customization, consider defining Spring's individual AnnotationBeanPostProcessors instead, e.g. CommonAnnotationBeanPostProcessor). However, the annotation-config element does not activate any kind of proxying or special exporting. For such purposes, Spring provides more specific configuration elements:

<tx:annotation-driven/>

This setting activates processing of transaction annotations, with the following two variants supported out of the box in Spring 2.5:

  • org.springframework.transaction.annotation.Transactional:
    Spring's own transaction annotation, as introduced in Spring 1.2. Allows for specifying propagation behavior (REQUIRED, REQUIRES_NEW, etc), read-only flag, custom isolation level (REPEATABLE_READ, SERIALIZABLE, etc) and custom rollback rules on a per-transaction level.
  • javax.ejb.TransactionAttribute
    EJB 3.0's transaction annotation. No customization options other than propagation behavior (REQUIRED, REQUIRES_NEW, etc).


Side note: As with all of Spring's support options, the EJB 3.0 TransactionAttribute annotation will only be available if the EJB 3.0 API is actually present in the classpath. Spring automatically adapts to the presence of that API, analogous to the JSR-250 API or the JPA API (as referenced above).

The <tx:annotation-driven> element allows for transaction-specific configuration, e.g. the Spring PlatformTransactionManager to talk to (through the "transaction-manager" attribute) and the mode to operate in:

<tx:annotation-driven transaction-manager="myTm" mode="aspectj"/>

The explicit AspectJ mode of transaction annotation processing is new in Spring 2.5, allowing to use Spring's AnnotationTransactionAspect instead of traditional AOP proxies. This requires AspectJ compile-time weaving or load-time weaving, modifying the byte code of classes that happen to use the @Transactional annotation. Such weaving allows for supporting the annotation on any kind of method: be it public, protected or private - be it an external call or a call from within the object - the transaction will always kick in as specified by the annotation. This is in sharp contrast to traditional AOP proxies, where annotation-driven transactions are limited to public method calls coming in through the proxy.

If your environment is capable of load-time weaving, then the following configuration is sufficient for enabling AspectJ-style transaction annotation processing. Note that this requires either a runtime environment with built-in weaving support (e.g. WebLogic 10, OC4J 10.1.3.1, Tomcat configured with Spring's TomcatInstrumentableClassLoader) or Spring's VM agent to be specified on JVM startup ("-javaagent:spring-agent.jar").

<context:load-time-weaver/>

<tx:annotation-driven mode="aspectj"/>

<bean id="transactionManager" class="…"/>

Finally, Spring 2.5 also provides a convenient configuration element for activating JMX exporting. The default MBeanServer will be autodetected on all common platforms, including the standard Java 5 platform MBeanServer as well as the special MBeanServers exposed by WebLogic 9/10 and WebSphere 6.

<context:mbean-export/>

Spring-managed beans may then implement standard MBean/MXBean conventions, qualifying as MBean classes according to the JMX specification, or use the following annotations to declare their management signature (as known since Spring 1.2):

  • org.springframework.jmx.export.annotation.ManagedResource:
    used at the type level to indicate a JMX-exposed component.
  • org.springframework.jmx.export.annotation.ManagedAttribute:
    used at the bean property setter/getter level to indicate an MBean attribute.
  • org.springframework.jmx.export.annotation.ManagedOperation:
    used at the public method level to indicate an exporter MBean operation.


This indicates the real power of Spring's annotation configuration model: Different configuration concerns seamlessly merge into a unified whole, with consistent configuration style and unified component lifecycle - it's all still a standard Spring bean underneath, managed by a Spring ApplicationContext!

So much for this brief tour through Spring's core configuration annotations. If you are interested in hearing more about what's new in Spring 2.5 and how it all ties together, let me invite you to this Wednesday's Spring 2.5 webinar where I will be covering all key feature areas in Spring 2.5, ranging from Java 6 support to annotation-based configuration!

Spring: Interface21 Team Blog

Spring Java Configuration Moving Ahead

Rod Johnson

Several users have asked whether we are committed to Spring Java Configuration, and how it sits with the annotation configuration option introduced in Spring 2.5. The answer is yes, we are committed to Java Config; and these two approaches are not mutually exclusive.

These two configuration approaches are quite different: the @Autowired annotation in the Spring Framework configures components using annotations in business objects, while Spring Java Config takes a unique approach of externalizing the annotations in dedicated configuration classes. Neither of these approaches is uniquely right or wrong, and they are compelling for different circumstances. There is even no reason that both couldn't be used in the same application.

If you think that Spring = XML it's time to rethink. (It was never strictly accurate, in any case, as the Spring core container has always used its own Java metadata, and doesn't know about XML or any other representation.)

This brings us to an important philosophical principle: our mission with Spring is to provide the best component model for enterprise Java, setting the standard for flexibility to meet complex requirements, and providing a comprehensive solution to real-world problems. We don't believe that there is any one size fits all model for configuration, and we believe in accommodating choice, within our strong, extensible model. However you choose to define your Spring-managed objects, they're eligible for the same rich set of enterprise services, unequaled third party integrations, true AOP, many extension points etc.

Thus Spring 2.5's @Component and @Autowired annotations, which cause the container to autodetect Spring-managed objects, can happily coexist with Java Configuration, XML and other configuration options.

This reminds me: I am talking about ways of configuring the Spring container at QCon in San Francisco later this week, and it should be interesting to get feedback. I'll see if I can post the slides here or on SpringFramework.org afterwards.

Spring Java Configuration was becalmed for a while due to Costin's commitment to Spring Dynamic Modules for OSGi, but it's now on track. I have done quite a bit of work on it over the last few days: updating it to Spring 2.5; removing unused code; and adding an often requested new feature–the externalization of configuration values, as well as beans.

While M2 runs fine on 2.5RC1 (quite a statement of 2.5's backward compatibility, given the depth of JavaConfig's use of Spring IoC), it contained its own annotation scanning code (which the Spring Framework adopted and took forward), so moving to the later Spring version made sense.

The new configuration property externalization feature takes a suggestion in JIRA to use abstract methods (thanks to Guillaume Duchesneau).

These methods are annotated with the new @ExternalValue annotation, as follows:

@Configuration
@ResourceBundles("classpath:/com/yourcompany/yourpackage/basename")
static abstract class ConfigurationExample {

        @Bean
        public Person john() {
                Person john= new Person();
                john.setName(getName());
                john.setAge(methodWithArbitraryNameReturningAge());          
                john.setBusy(busy());
                return john;
        }
               
        // Property name defaults to method name.
        // In the case of a getter method, it's the property name–
        // "name" in this case
        @ExternalValue
        public abstract String getName();
               

        // Property name is taken from annotation value
        @ExternalValue("age")                 
        public abstract int methodWithArbitraryNameReturningAge();
               
        @ExternalValue
        protected abstract boolean busy();
               
}

Spring Java Config subclasses such classes to implement those methods to return the externalized properties at runtime. (It subclasses configuration classes anyway, for other reasons, such as caching singleton bean method return values.) The methods can be public or protected.

The @ResourceBundles annotation on the configuration class identifies one or more resource bundles to use to resolve values, which can be identified through the method name or through an explicit String value on the annotation. The locations are Spring resource location Strings.

Methods annotated with @ExternalBean can be concrete, in which case the actual return value will be used if no external value is found, like this:

@ExternalValue
public int otherNumber() {
        return 25;
}

This usage means that value is externalizable, but externalizing it is optional, as with a bean property with a usable default.

As you would expect, the properties file for the example looks like this:

name=John Doe
age=45
busy=false

The underlying mechanism is designed to be extensible, so properties files are not the only option, and we will provide additional options in future releases. The abstract method approach allows for dynamically sourced values: for example, from a database, or custom, from another system.

Right now, the example only works from SVN, but we are planning a M3 release this month. Moving forward, Chris Beams, a new Interface21 consultant based in Seattle, will be working on this project. At Interface21, we believe that all our technical staff should do everything we do as a company: developing products, consulting and training. Product developers deliver some training and consulting; service delivery staff work on projects. This ensures that everyone gets to contribute to the open source projects we all care about, and that everyone stays grounded in real world business requirements, rather than developing infrastructure in glorious isolation (a danger seen in J2EE in the past). Chris does mainly consulting and training, but he will be "aligned" with Spring Java Config, making it his main development focus, so he should be spending significant time on development, with help from Costin and myself.

How long it takes to get Spring Java Config to 1.0 final partly depends on you. We need feedback on usage in anger; we need feature requests (although we'll probably want to keep the scope manageable for 1.0); and we need help in prioritization. If you want this, tell us and we'll listen!

Spring: Interface21 Team Blog

Source for demos shown at NL-JUG session June 13th 2007

Alef Arendsen

Yesterday, Joris and I gave a session at the Dutch Java Users Group. We did the session twice and had about 250 people in total attending the sessions. A lot of people asked for the code for the demos we did during the sessions. Attached you'll find the code for the AOP and Dependency Injection demos. It shows a simple aspect flushing the Hibernate session before every JDBC operation (not as robust as you'd want it in production code, but it's a start) and it also shows the CarPlant system (demo'd before in other sessions and previously attached to another blog entry) configured using the various to do Dependency Injection in Spring 2.1 (i.e. using <bean>, @Bean and @Autowired).

It's a Maven2 project, so you'll need to have Maven2 installed. To prepare an Eclipse project including all libraries, run mvn eclipse:eclipse at the command line in the carplant directory.

The sources: carplant.zip

During the session a question came up about multiple <aop:config> blocks inside one application contexts. The guy in the audience wasn't sure if two or more blocks of AOP configuration showed the expected result (advising two or more times). I don't have the guys email address, so I wanted to clarify this here a little bit. Consider the following code. The doIt() will be advised. The actual advice (for simplicity) is kept in the same class, just as the main method bootstrapping the ApplicationContext.

public class Logger {

  public void doIt() {

  }

  public void log() {
    System.out.println("Log!");
  }

  public static void main(String args[]) {
    ApplicationContext context =
      new ClassPathXmlApplicationContext(
        new String[] {"com/carplant/context1.xml", "com/carplant/context2.xml"});

    Logger logger = (Logger)context.getBean("logger");

    logger.doIt();
  }
}

Configuration 1: one simple AOP config block

The file context2.xml is empty in this case, whereas context1.xml contains the following code:

<bean id="logger" class="Logger"/>

<aop:config>
        <aop:pointcut id="doItOperation" expression="execution(* doIt(..))"/>
        <aop:aspect ref="logger">
                <aop:before pointcut-ref="doItOperation" method="log"/>
        </aop:aspect>
</aop:config>

As expected, upon calling the doIt() method we'll only get one line of output from the logger (it's only advised once).

Configuration 2: two AOP config blocks in two different files

context2.xml now is identical to context1.xml (in the example above) with the only difference that in context2.xml we don't have bean called logger. When running this scenario, we'll see two Log! output entries. The doIt() method is advised twice.

Configuration 3: two AOP config blocks in the same configuration file

context2.xml is empty again. context1.xml on the other hand now contains two <aop:config> blocks. The only difference between the two is the pointcut identifier (this is an XML ID, so should be unique in the XML file).

<bean id="logger" class="Logger"/>

<aop:config>
        <aop:pointcut id="doItOperation" expression="execution(* doIt(..))"/>
        <aop:aspect ref="logger">
                <aop:before pointcut-ref="doItOperation" method="log"/>
        </aop:aspect>
</aop:config>

<aop:config>
        <aop:pointcut id="doItOperation2" expression="execution(* doIt(..))"/>
        <aop:aspect ref="logger">
                <aop:before pointcut-ref="doItOperation2" method="log"/>
        </aop:aspect>
</aop:config>

Running this will also show that the bean will be advised twice.

Note that I'm using a 2.1 milestone release here.

Spring: Interface21 Team Blog

Code samples from SpringOne 'Beyond the obvious' talk

Joris Kuipers

Last week at SpringOne, Alef and I gave a talk on dealing with complex applications using Spring. Complexity in this case was considered both at the structural and dynamic level. As for the structural part of the talk, I covered that one in my previous blog posting. The dynamic part explained some possible solutions to deal with differences between your deployment environments. (testing, acceptance, production, etc.)
A lot of people asked me if I could provide them with the source of the demonstrations I gave during the talk. I've attached the sources to this blog entry and will explain briefly how this all works. Hopefully the talk itself will eventually become available on parleys.com later this year, so you can get some more background information on the topic.

Environmental Awareness: Support your runtime environment

In the talk I argued that dealing with differences between your environments by using custom build scripts that generate deployment units per environment comes with several disadvantages. One of those is that you cannot reuse your build artifacts (war or ear files) when your application promotes from for example your acceptance environment to your production environment. In order to address these disadvantages, you have to make your application environment aware: come up with some way to determine in what environment your app is running and then configure your app to react to that.

There are several ways to do this: in a Spring-application, the obvious way to enable environment-dependent behaviour is to have different bean definitions for each environment that requires non-default configuration. I've shown three ways to do that:

  • The first is to load extra context configuration files for certain environments. By using bean definition inheritance and overrides you can then take the appropiate actions at configuration time. When you use a ContextLoaderListener to configure your web application context, this requires some extra code, which is shown in the web project in the attached samples. BTW, credits for this idea should go to a former collegue of mine (Ezra, thanks!)
  • The second is to use JavaConfig instead of XML to define your environment-dependent beans. Where you determine what beans to create is then moved from determining what config files to load to your JavaConfig class.
  • The last sample combines the previous two to determine what JavaConfig class to use, where subclasses that extend a common base configuration are created for each environment. This showcases the power of having your configuration in an actual class: you can use regular java inheritance and polymorphism, which blurs the distinction between bean definiton inheritance and class inheritance.

Other ways could include custom FactoryBean-implementations, for example.

The samples

The samples demonstrate the use of a simple service and dao that find a Person's last name by first name. In the default case, only two persons are defined (Alef and I). In a development environment, we'll use a static dao implementation instead that always returns a John Doe. In an acceptance environment, a third person (our collegue Arjen) is defined. The integration tests check if the correct behaviour is exposed by our application in each environment.

There are several ways you can check in what environment your application is running: for these samples, I've used a system property that is being used by the EnvironmentUtils class. Other ways could be to examine the database or a JNDI registry, for example.

Instead of just zipping up my Eclipse workspace, I've created a Maven sample: several people have tried to convince me to give Maven a second chance lately, after I had turned away from it in disgust a couple of years ago. I have to admit that Maven 2 is actually a lot better than Maven 1, although the generation of Eclipse workspace artifacts for web projects could use some improvement (like WTP 2 support). I missed some other stuff too, but that's probably just an utter lack of experencience on my part. The good thing is that I now do not have to package all the dependencies in my sample.

After installing Maven, you can run the sample tests by running 'mvn test' from the root directory. To generate Eclipse projects from the samples, run the following command: 'mvn -DdownloadSources=true eclipse:eclipse'. To build the jars and war, use 'mvn package' or 'mvn install' to also add the build artifacts to your local repository.

The war contains a single servlet accessible as '/[context-root]/env': to see the difference for each environment, start your servlet container with a system property called 'app.env' which holds the environment letter (D, T, A or P). So, -Dapp.env=D added to the startup line of your server would cause the application to run in development mode, which means that all last names returned will be 'Doe'.

Spring: Interface21 Team Blog

Setter injection versus constructor injection and the use of @Required

Alef Arendsen

A couple of month ago, we start publishing polls on www.springframework.org asking people to provide their feedback about Spring, some of its features and how they are using those features. The first question I posted was whether or not people were checking required dependencies and if so, what mechanisms they used. I quickly followed up on this question asking the community what transaction management strategy it used.

To my delight when I first checked the results, back in March, a lot of people told us by voting in the first poll that they were using the @Required annotation. The second poll–on transaction management, quickly showed that a lot of people were using the @Transactional annotation. Below you can find some of the results of the poll about checking required dependencies. Together with the poll on transaction management (about 30% of all respondents are using the @Transactional annotation to demarcate transaction boundaries) they consistently show that people are using Spring 2.0 a lot, which was very good news for us. Because upgrading an application that uses Spring 1.x to use Spring 2.0 shouldn't be any issue, we really hoped people would not stick to Spring 1.x and in fact, people massively upgraded.

How are you checking required dependencies

8% I check them in my business methods
9% Using init-method and an assert mechanism (c.f. Assert)
9% Using the dependency-check attribute in XML
13% I don't have to, I use constructor injection
15% Using InitializingBean and an assert mechanism
17% Using the Spring 2.0 @Required annotation
29% I do not check required dependencies

What's interesting however is that 29 percent of all people do not check required dependencies. In the forum thread that accompanied the discussion, interesting suggestions came up as to why some people weren't doing this and how people solved it otherwise. Let's review some of those.

Constructor injection

I'd like to begin with reviewing constructor injection. Any object that has a constructor that takes arguments, can (obviously) not be constructed without passing in arguments. In Java, we have a default or implicit constructor added to our class as long as we do not add one ourselves. This default or implicit constructor does not take arguments, so as long as you do not add a constructor with arguments at all, or specifically add one without any arguments, it will be possible for Spring (or any other user of your class for that matter) to instantiate your class without passing it anything.

In other words, we can force a user of our class (again, this might be Spring but it could also be a unit test that instantiates your class directly) to instantiate it while passing in arguments.

public class Service {

  public Collaborator collaborator;

  // constructor with arguments, you *have* to
  // satisfy the argument to instantiate this class
  public Service(Collaborator collaborator) {
    this.collaborator = collaborator;
  }
}

We can use this to our advantage when in need to check required dependencies. If we modify the above code example to include assertions, we are 100% sure the class will never be instantiated without its collaborators injected:

public Service(Collaborator collaborator) {
  if (collaborator == null) {
    throw new IllegalArgumentException("Collaborator cannot be null");
  }
  this.collaborator = collaborator;
}

In other words, we do not need a dependency checking mechanism if we're using constructor injection in combination with an assertion mechanism like I've showed above.

Why do people not use constructor injection mostly

The question of course now is, why so few people are using constructor injection to enforce required dependencies, if it is the simplest way to get the job done! There are two reasons for this–one is a bit more historical, the other being the nature of the Spring Framework itself.

Historical reasons

Early 2003, when Spring was first published as an open source project, it primarily focused on setter injection. Other frameworks also pioneered ways of doing dependency injection and one of those was PicoContainer, which strongly focused on constructor injection. Spring maintained its focus on setter injection because at the time, we believed that the lack of default arguments and argument names for constructor arguments resulted in less clarity for developers. We however also implemented constructor injection, to be able to offer that feature to developers that wanted to instantiate and manage objects they didn't control.

This is one of the reasons why you're seeing a lot of setter injection throughout the Spring Framework itself. The fact that setter injection was used in Spring itself, as well as us advocating it mostly also caused many pieces of third-party software to start using setter injection as well as blog and articles to start mentioning setter injection.

(By the way, do people still remember type 1, 2 and M inversion of control ;-) )

Frameworks need to be a lot more configurable

The second reason why setter injection is used a lot more often than you would expect, is the fact that frameworks like Spring in general, are much more suited to be configured by setter injection than by constructor injection. This is mostly because frameworks that need to be configured often contain lots of optional values. Making optional values configurable using constructor injection would lead to needless clutter and proliferating constructors, especially when used in combination with class inheritance.

For those exact two reasons, I think constructor injection is much more usable for application code than it is for framework code. In application code, you inherently have a lesser need for optional values that you need to configure (you're application code is less likely to be used in many situations, which would require configurable properties). Second of all, application code uses class inheritance a lot less often than framework code does. Specialization in an application does not occur as often in application code as it does in framework code for example–again the number of use cases in which application code is far less.

So what should you use?

We usually advise people to use constructor injection for all mandatory collaborators and setter injection for all other properties. Again, constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state (not having passed its collaborators). In other words, when using constructor injection you do not have to use a dedicated mechanism to ensure required properties are set (other than normal Java mechanisms).

One of the other arguments for not using constructor injection is the lack of argument names in constructors and the fact that these do not appear in the XML. I would argue that in most applications, this does not matter that much. First consider the variant that uses setter injection:

<bean id="authenticator" class="com.mycompany.service.AuthenticatorImpl"/>

<bean id="accountService" class="com.mycompany.service.AccountService">
  <property name="authenticator" ref="authenticator"/>
</bean>

This version mentions the authenticator as a property name as well as a bean name. This is the pattern that I frequently encounter. I would argue that while using constructor injection, the lack of constructor argument names (and those not appearing in XML), doesn't really confuse us a lot.

<bean id="authenticator" class="com.mycompany.service.AuthenticatorImpl"/>

<bean id="accountService" class="com.mycompany.service.AccountService">
  <constructor-arg ref="authenticator"/>
</bean>

Using the alternative mechanisms

That brings us back to the topic of this blog entry, which also included a mention of @Required. This the new Spring 2.0 annotation we introduced back in 2006. @Required allows you to instruct Spring to check required dependencies for you. In case you are not in the position to use constructor injection, or for whatever other reasons, you prefer setter injection, @Required is the way to go. Annotation a property's setter an registering the RequiredAnnotationBeanFactoryPostProcessor as a bean in your application context is all you need to do:

public class Service {

  private Collaborator collaborator;

  @Required
  public void setCollaborator(Collaborator c) {
    this.collaborator = c;
  }
}

<bean class="org.sfw.beans.factory.annotation.RequiredAnnotationBeanFactoryPostProcessor"/>

Other mechanisms to check required dependencies

There are a few other mechanisms to enforce the checking of required dependencies. Most of those rely on Spring's ability to allow you to get callbacks at certain points in the construction an initialization of an object, such as the Spring InitializingBean interface or Spring's an arbitrary init method you can configure in the XML (using the init-method attribute). Those all resemble the use of constructor injection a lot, with the difference that you are relying on Spring to call the method in which the assertions take place for you.

public class Service implements InitializingBean {

  private Collaborator collaborator;

  public void setCollaborator(Collaborator c) {
    this.collaborator = c;
  }

  // from the InitializingBean interface
  public void afterPropertiesSet() {
    if (collaborator == null) {
      throw new IllegalStateException("Collaborator must be set in order for service to work");
    }
  }
}

Another mechanism, similar to @Required in Java is the dependency-check attribute in XML, which strangely enough is not used all that much. Enabling the dependency check by tweaking this attribute (it's turned off by default) will tell Spring to start checking certain dependencies on beans. Refer to the reference for more information about this features.

So why NOT check required dependencies

There are a lof of people that actually do not check if dependencies have been accurately set. The biggest reason people gave for not doing so is because they would find out quickly enough is they fired up the ApplicationContext and somehow used the classes that had dependencies. This is of course very true. If you're using Spring's integration testing support for example, you can have Spring load up an application context for you. If you're also making sure some of the actual code gets tested in your integration test, you can probably pretty much guarantee all the dependencies the classes need to work are set. It is an approach that bugs me a little bit though. You have to be confident in your test cases covering your code enough though, because if your tests do not test the code that depends on the collaborators being set, you're screwed, as you might not detect things! Of course a smoke test when you are deploying your application would probably do the trick right then and there, but I wouldn't want to be the one that only finds out about missing dependencies at runtime!

Conclusion

There is a lot to be said about constructor injection versus setter injection and I know a lot of people still prefer setter injection. I think though (and with me a lot of people) that constructor injection in combination with checking dependencies in your constructor is the better way (for code that does not have a lot of optional and configurable values or collaborators) to enforce checking of required dependencies. Combining this with final fields immediately gives you the other benefit of increased safety in a multi-threaded environment and because usually that does not prove to be a big deal anyway, I'm not going to touch on that in this blog entry.

There are situations in which I would not use constructor injection. One of those for example is a class with a lot of dependencies or other configurable values. I personally do not consider a constructor with 20 arguments as a good example of nice code. Of course, the question is, if a class with 20 dependencies does not have too many responsibilities…

One thing is for sure–enforcing required dependencies by checking them in your business methods is something I would certainly not do.

Spring: Interface21 Team Blog