» tagged pages
» logout

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

WEB4J - Minimalist Java Web Application Framework -> Criticisms of Spring, PHP, and Rails

Criticizing Spring beyond the obvious "too much xml": Spring is huge. Spring has many bad names for things. Spring confuses coding with configuration. Spring has too many parallel mechanisms, etc.

XML: del.icio.us/tag/xml

Introducing Inject4Spring (IoC for Sping metadata) - SoftAMIS-42

specifying dependencies in Spring context using "opposite" direction of references

User:jeyrb: del.icio.us/subscriptions/jey

Introducing Inject4Spring (IoC for Sping metadata) - SoftAMIS-42

specifying dependencies in Spring context using "opposite" direction of references

OSGi: del.icio.us/tag/OSGi

Spring - Chapter 12. Data Access using O/R Mappers

Chapter 12. Data Access using O/R Mappers

Hibernate: del.icio.us tag/hibernate

impala - Google Code

"Impala is a dynamic module framework for Java enterprise application development. Impala builds on the Spring Framework to provide a genuinely modular, highly productive environment for web-based applications."

OSGi: del.icio.us/tag/OSGi

impala - Google Code

"Impala is a dynamic module framework for Java enterprise application development. Impala builds on the Spring Framework to provide a genuinely modular, highly productive environment for web-based applications."

User:jeyrb: del.icio.us/subscriptions/jey

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

The Rich Engineering Heritage Behind Dependency Injection

Great article on dependency injection and architectures description languages

Spring: del.icio.us/tag/SpringFramework

Page 1 | Next >>