Archive

Archive for the ‘Books’ Category

Defining Bean Properties by Shortcut

2010年09月14日 Leave a comment

    Spring supports a shortcut for specifying the value of a simple type property. You can present a value attribute in the <property> element instead of enclosing a <value> element inside.

    Since Spring 2.0 another convenient shortcut to define properties was added. It consists of using the p schema to define bean properties as attributes of the <bean> element. This can shorten the lines of XML configuration.

Categories: Books

Declaring Beans in the Bean Configuration File

2010年09月13日 Leave a comment

    Each bean should provide a unique name or id and a fully qualified class name for the Spring IoC container to instantiate it. For each bean property of simple type (e.g., String and other primitive types), you can specify a <value> element for it. Spring will attempt to convert your value into the declaring type of this property. To configure a property via setter injection, you use the <property> element and specify the property name in its name attribute. A <property> requires that the bean contain a corresponding setter method.

    You can also configure bean properties via constructor injection by declaring them in the <constructor-arg> elements. There’s not a name attribute in <constructor-arg>, because constructor arguments are position-based.

    In the Spring IoC container, each bean’s name should be unique, although duplicate names are allowed for overriding bean declaration if more than one context is loaded. A bean’s name can be defined by the name attribute of the <bean> element. Actually, there’s a preferred way of identifying a bean: through the standard XML id attribute, whose purpose is to identify an element within an XML document. In this way, if your text editor is XML-aware, it can help to validate each bean’s uniqueness at design time.

    However, XML has restrictions on the characters that can appear in the XML id attribute. But usually, you won’t use those special characters in a bean name. Moreover, Spring allows you to specify multiple names, separated by commas, for a bean in the name attribute. But you can’t do so in the id attribute because commas are not allowed there.

    In fact, neither the bean name nor the bean ID is required for a bean. A bean that has no name defined is called an anonymous bean. You will usually create beans like this that serve only to interact with the Spring container itself, that you are sure you will only inject by type later on, or that you will nest, inline, in the declaration of an outer bean.

Categories: Books

Creating the Bean Configuration File

2010年09月13日 Leave a comment

    To declare beans in the Spring IoC container via XML, you first have to create an XML bean configuration file with an appropriate name, such as beans.xml. You can put this file in the root of the classpath for easier testing within an IDE.

    The Spring configuration XML allows you to use custom tags from different schemas (tx, jndi, jee, and so on) to make the bean configuration simpler and clearer. Here’s an example of the simplest XML configuration possible.

Categories: Books

Bash

2010年09月9日 Leave a comment

    Although most users think of the shell as an interactive command interpreter, it is really a programming language in which each statement runs a command. Because it must satisfy both the interactive and programming aspects of command execution, it is a strange language, shaped as much by history as by design.

    The shell is a programming language. Don’t let anyone tell you otherwise. The shell is not just glue that sticks bits together. The shell is a lot more than a tool that runs other tools. The shell is a complete programming language!

    When a Linux user asked me about membership databases, I asked him what he really needed. He wanted to store names and addresses for a couple of hundred members and print mailing labels for each of them. I recommended using a text editor to store the information in a text file, and I provided a shell script to create the labels in PostScript. (The script, ps-labels, appeared in my first book, Shell Scripting Recipes: A Problem-Solution Approach.)

    When the SWEN worm was dumping hundreds of megabytes of junk into my mailbox every few minutes, I wrote a shell script to filter them out on the mail server and download the remaining mail to my home computer. That script has been doing its job for several years.

    I used to tell people that I did most of my programming in the shell but switched to C for anything that needed the extra speed. It has been several years since I have needed to use C, so I no longer mention it. I do everything in the shell.

    A shell script is as much a program as anything written in C, Python, or any other language. Just because shell scripts are easier to write doesn’t mean they should take a backseat to compiled programs or other scripting languages. I use the terms script and program interchangeably when referring to tasks written in the shell.

Why the Shell?

    Some Linux users do all of their work in a GUI environment and never see a command line. Most, however, use the shell at least occasionally and know something about Unix commands. It’s not a big step from there to saving oft-repeated commands in a script file. When they need to extend the capabilities of their system, the shell is the natural way to go.

    The shell also has important advantages over other programming languages:

  • It interfaces simply and seamlessly with the hundreds of Unix utilities.
  • It automatically expands wildcards into a list of file names.
  • Lists contained in a variable are automatically split into their constituent parts.
Categories: Books

Configuring Beans in the Spring IoC Container

2010年09月7日 Leave a comment

Problem

    Spring offers a powerful IoC container to manage the beans that make up an application. To utilize the container services, you have to configure your beans to run in the Spring IoC container.

Solution

    You can configure your beans in the Spring IoC container through XML files, properties files, annotations, or even APIs.

    Spring allows you to configure your beans in one or more bean configuration files. For a simple application, you can just centralize your beans in a single configuration file. But for a large application with a lot of beans, you should separate them in multiple configuration files according to their functionalities (e.g., controllers, DAO, and JMS). One useful division is by the architectural layer that a given context services.

How It Works

    Suppose that you are going to develop an application for generating sequence numbers. In this application, there may be many series of sequence numbers to generate for different purposes. Each one of them will have its own prefix, suffix, and initial value. So you have to create and maintain multiple generator instances in your application.

Creating the Bean Class

    In accordance with the requirements, you create the SequenceGenerator class that has three properties prefix, suffix, and initial – that can be injected via setter methods or a constructor. The private field counter is for storing the current numeric value of this generator. Each time you call the getSequence() method on a generator instance, you will get the last sequence number with the prefix and suffix joined. You declare this method as synchronized to make it thread-safe.

    As you see, this SequenceGenerator class can be configured by getters/setters or by the constructor. When configuring them with the container, this is called constructor injection and setter injection.

Creating the Bean Configuration File

    To declare beans in the Spring IoC container via XML, you first have to create an XML bean configuration file with an appropriate name, such as beans.xml. You can put this file in the root of the classpath for easier testing within an IDE.

    The Spring configuration XML allows you to use custom tags from different schemas (tx, jndi, jee, and so on) to make the bean configuration simpler and clearer. Here’s an example of the simplest XML configuration possible.

Categories: Books

How It Works

2010年09月5日 Leave a comment

Instantiating an Application Context

    ApplicationContext is an interface only. You have to instantiate an implementation of it. The ClassPathXmlApplicationContext implementation builds an application context by loading an XML configuration file from the classpath. You can also specify multiple configuration files for it.

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    Besides ClassPathXmlApplicationContext, several other ApplicationContext implementations are provided by Spring. FileSystemXmlApplicationContext is used to load XML configuration files from the file system or from URLs, while XmlWebApplicationContext and XmlPortletApplicationContext can be used in web and portal applications only.

Getting Beans from the IoC Container

    To get a declared bean from a bean factory or an application context, you just make a call to the getBean() method and pass in the unique bean name. The return type of the getBean() method is java.lang.Object, so you have to cast it to its actual type before using it.

SequenceGenerator generator = (SequenceGenerator) context.getBean("sequenceGenerator");

    Up to this step, you are free to use the bean just like any object you created using a constructor. The complete source code for running the sequence generator application is given in the following Main class:

package com.apress.springrecipes.sequence;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {

        ApplicationContext context =
            new ClassPathXmlApplicationContext("beans.xml");

        SequenceGenerator generator =
            (SequenceGenerator) context.getBean("sequenceGenerator");

        System.out.println(generator.getSequence());
        System.out.println(generator.getSequence());
    }
}
Categories: Books

Instantiating the Spring IoC Container

2010年09月5日 Leave a comment

Problem

    You have to instantiate the Spring IoC container for it to create bean instances by reading their configurations. Then, you can get the bean instances from the IoC container to use.

Solution

    Spring provides two types of IoC container implementation. The basic one is called bean factory. The more advanced one is called application context, which is a compatible extension to the bean factory. Note that the bean configuration files for these two types of IoC containers are identical.

    The application context provides more advanced features than the bean factory while keeping the basic features compatible. So we strongly recommend using the application context for every application unless the resources of this application are restricted, such as when running in an applet or a mobile device.

    The interfaces for the bean factory and the application context are BeanFactory and ApplicationContext, respectively. The interface ApplicationContext is a subinterface of BeanFactory for maintaining compatibility.

Note

    In order to compile and run the Spring code presented in this chapter and all subsequent chapters, you’ll need to have the dependencies for the Spring framework on your classpath. The recommended way to do this is using a build management solution like Apache Maven or Apache Ant and Ivy. If you are using Maven, add the dependencies listed below to your Maven project. Here, as elsewhere, we use the notation ${spring.version} to refer to the version. Replace this with the version that is most relevant to you. This book was written and compiled against the version 3.0.2.RELEASE.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
</dependency>
Categories: Books

How This Book Is Structured

2010年09月5日 Leave a comment

    Chapter 1, "Introduction to Spring", gives a general overview of the Spring framework: how to set it up, what it is, and how it’s used.

    Chapter 2, "Advanced Spring IoC Container", reviews concepts that, while not as widely used as those discussed in Chapter 1, are still key to fully exploiting the container.

    Chapter 3, "Spring AOP and AspectJ Support", discusses Spring’s support for aspect-oriented programming using AspectJ. This technology underlies many of the other services provided by the Spring framework.

    Chapter 4, "Scripting in Spring", discusses using scripting languages like Groovy, BeanShell, and JRuby with the Spring framework.

    Chapter 5, "Spring Security", provides an overview of the Spring Security project, formerly Acegi, to help you better secure your application.

    Chapter 6, "Integrating Spring with Other Web Frameworks", introduces the core web-tier support that Spring provides. This provides a base for all technologies that Spring provides in the web tier.

    Chapter 7, "Spring Web Flow", provides an introduction of Spring Web Flow, which lets you build UIflows on the web tier.

    Chapter 8, "Spring @MVC", covers web-based application development using the Spring Web MVC framework.

    Chapter 9, "Spring REST", provides an introduction to Spring’s support for RESTful web services.

    Chapter 10, "Spring and Flex", discusses using Spring BlazeDS to integrate your rich Internet application (RIA) with Spring beans. Additionally, this chapter gives an introduction to Spring ActionScript, to let users writing Flash applications in ActionScript enjoy the same container services and conveniences as Java Spring developers do.

    Chapter 11, "Grails", discusses the Grails framework, with which can increase your productivity by using best-of-breed pieces and gluing them together with Groovy code.

    Chapter 12, "Spring Roo", covers Spring Roo, the pivotal new framework from SpringSource designed toprovide a force-multiplying framework for Java developers.

    Chapter 13, "Spring Testing", discusses unit testing with the Spring framework.

    Chapter 14, "Spring Portlet MVC Framework", covers using the Spring MVC Portlet framework to build applications and leverage the strengths of the Portlet container.

    Chapter 15, "Data Access", discusses using Spring to talk to data stores using APIs like JDBC, Hibernate, and JPA.

    Chapter 16, "Transaction Management in Spring", introduces the concepts behind Spring’s robust transaction management facilities.

    Chapter 17, "EJB, Spring Remoting, and Web Services", introduces you to the various facilities for RPC, including the Spring Web Services project.

    Chapter 18, "Spring in the Enterprise", discusses many utilities provided by the Spring platform like JMX support, scheduling, and e-mail support.

    Chapter 19, "Messaging", discusses using Spring with message-oriented middleware through JMS and the simplifying Spring abstractions.

    Chapter 20, "Spring Integration", discusses using the Spring Integration framework to integration
disparate services and data.

    Chapter 21, "Spring Batch", introduces the Spring Batch framework, which provides a way to model
solutions traditionally considered the domain of mainframes.

    Chapter 22, "Distributed Spring", talks about various ways of taking scaling Spring using distributed state and grid processing.

    Chapter 23, "Spring and jBPM", introduces you to business process management concepts and how to integrate one popular framework, JBoss’ jBPM, with the Spring framework.

    Chapter 24, "OSGi and Spring", walks you through the robust support for OSGi provided by the Spring framework.

Categories: Books

Who this Book is for

2010年09月5日 Leave a comment

    This book is for Java developers who want to simplify their architecture and solve problems outside the scope of the Java EE platform. If you are already developing using Spring in your projects, the more advanced chapters present discussions of newer technologies that you might not know about already. If you are new to the framework, this book will get you started in no time.

    This book assumes that you have some familiarity with Java and an IDE of some sort. While it is possible, and indeed useful, to use Java exclusively with client applications, Java’s largest community lives in the enterprise space and that, too, is where you’ll see most of these technologies deliver the most benefit. Thus, some familiarity with basic enterprise programming concepts like the Servlet API is assumed.

Categories: Books

Java

2010年09月4日 Leave a comment

    The Spring framework is growing. It has always been about choice. Java EE focused on a few technologies, largely to the detriment of alternative, better solutions. When the Spring framework debuted, few would have agreed that Java EE represented the best-in-breed architectures of the day. Spring debuted to great fanfare, because it sought to simplify Java EE. Each release since marks the introduction of new features designed to both simplify and enable solutions.

    With version 2.0 and later, the Spring framework started targeting multiple platforms. The framework provided services on top of existing platforms, as always, but was decoupled from the underlying platform wherever possible. Java EE is a still a major reference point, but it’s not the only target. OSGi (a promising technology for modular architectures) has been a big part of the SpringSource strategy here. Additionally, the Spring framework runs on Google App Engine. With the introduction of annotation-centric frameworks and XML schemas, SpringSource has built frameworks that effectively model the domain of a specific problem, in effect creating domain-specific languages (DSLs). Frameworks built on top of the Spring framework have emerged supporting application integration, batch processing, Flex and Flash integration, GWT, OSGi, and much more.

    When it came time to update the seminal Spring Recipes, we quickly discovered that it’s been a long time since there was, effectively, only one core Spring framework. The SpringSource portfolio, such as it is, describes several frameworks, each of which is dramatically more capable than the alternatives with which it competes in other products. This book will serve you well on your journey through the various frameworks. If you don’t need these technologies, you don’t need to use them or add them to your project. If you do, it’s nice to know they’re available for you.

Categories: Books