Search the Web for JAVA Answers:

Search the Web for more JAVA Answers:
Hint: Press Ctrl+ to increase the font size of this blog and Ctrl- to decrease the font size of this blog.

Spring Concepts

The Spring Framework is an open source application framework for the Java platform and .NET Framework(Spring.NET).



Modules

The Spring Framework comprises several modules that provide a range of services:
  • Inversion of Control container: configuration of application components and lifecycle management of Java objects
  • Aspect-oriented programming: enables implementation of cross-cutting routines
  • Data access: working with relational database management systems on the Java platform using JDBC and object-relational mapping tools
  • Transaction management: unifies several transaction management APIs and coordinates transactions for Java objects
  • Model-view-controller: a HTTP and Servlet-based framework providing hooks for extension and customization
  • Remote Access framework: configurative RPC-style export and import of Java objects over networks supporting RMICORBA and HTTP-based protocols includingweb services (SOAP)
  • Convention-over-configuration: a rapid application development solution for Spring-based enterprise applications is offered in the Spring Roo module
  • Batch processing: a framework for high-volume processing featuring reusable functions including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management
  • Authentication and authorization: configurable security processes that support a range of standards, protocols, tools and practices via the Spring Security sub-project (formerly Acegi Security System for Spring).
  • Remote Management: configurative exposure and management of Java objects for local or remote configuration via JMX
  • Messaging: configurative registration of message listener objects for transparent message consumption from message queues via JMS, improvement of message sending over standard JMS APIs
  • Testing: support classes for writing unit tests and integration tests

Inversion  of Control:
Inversion of Control, or IoC, is an abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to procedural programming.

In traditional programming the flow is controlled by a central piece of code. Using Inversion of Control this central control as a design principle is left behind. Although thecaller will eventually get its answer, how and when is out of control of the caller. It is the callee who decides how and when to answer. Inversion of Control as a design guideline serves the following purposes:
-There is a decoupling of the execution of a certain task from implementation.
-Every system can focus on what it is designed for.
-Every system does not make assumptions about what other systems do or should do.
-Replacing systems will have no side effect on other systems.



In Java there are six basic techniques to implement Inversion of Control. These are:
  1. using a factory pattern
  2. using a service locator
  3. using a constructor injection
  4. using a setter injection
  5. using an interface injection
  6. using a contextualized lookdown

Dependency Injection:
Dependency injection (DI) in object-oriented computer programming is a technique for supplying an external dependency (i.e. a reference) to a software component - that is, indicating to a part of a program which other parts it can use. It is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency.

Without the concept of dependency injection, a consumer who needs a particular service in order to accomplish a certain task would be responsible for handling the life-cycle (instantiating, opening and closing streams, disposing, etc.) of that service. Using the concept of dependency injection, however, the life-cycle of a service is handled by a dependency provider (typically a container) rather than the consumer. The consumer would thus only need a reference to an implementation of the service that it needed in order to accomplish the necessary task.

Such a pattern involves at least three elements: a dependent, its dependencies and an injector (sometimes referred to as a provider or container). The dependent is a consumer that needs to accomplish a task in a computer program. In order to do so, it needs the help of various services (the dependencies) that execute certain sub-tasks. The provider is the component that is able to compose the dependent and its dependencies so that they are ready to be used, while also managing these objects' life-cycles. This injector may be implemented, for example, as a service locator, an abstract factory, a factory method or a more complex abstraction such as aframework.

The following is an example. A car (the consumer) depends upon an engine (the dependency) in order to move. The car's engine is made by an automaker (the dependency provider). The car does not know how to install an engine into itself, but it needs an engine in order to move. The automaker installs an engine into the car and the car utilizes the engine to move.

When the concept of dependency injection is used, it decouples high-level modules from low-level services. The result is called the dependency inversion principle.



Aspect Oriented Programming:

Aspect Oriented Programming (AOP) is a promising new technology for separating crosscutting concerns that are usually hard to do in object-oriented programming. This article aims to be an introductory point to the basic concepts associated with this new paradigm.

Object Oriented Programming

Nowadays, object-oriented programming (OOP) has become the mainstream programming paradigm where real world problems are decomposed into objects that abstract behavior and data in a single unit.

OOP encourages software re-use by providing design and language constructs for modularity, encapsulation, inheritance, and polymorphism. Although OOP has met great success in modeling and implementing complex software systems, it has its problems. Practical experience with large projects has shown that programmers may face some problems with maintaining their code because it becomes increasingly difficult to cleanly separate concerns into modules. An attempt to do a minor change in the program design may require several updates to a large number of unrelated modules.

Crosscutting Concerns

An example of crosscutting concerns is "logging," which is frequently used in distributed applications to aid debugging by tracing method calls. Suppose we do logging at both the beginning and the end of each function body. This will result in crosscutting all classes that have at least one function. Other typical crosscutting concerns include context-sensitive error handling, performance optimization, and design patterns.

Aspect Oriented Programming

AOP is a new technology for separating crosscutting concerns into single units called aspects. An aspect is a modular unit of crosscutting implementation. It encapsulates behaviors that affect multiple classes into reusable modules. With AOP, we start by implementing our project using our OO language (for example, Java), and then we deal separately with crosscutting concerns in our code by implementing aspects. Finally, both the code and aspects are combined into a final executable form using an aspect weaver. As a result, a single aspect can contribute to the implementation of a number of methods, modules, or objects, increasing both reusability and maintainability of the code. Figure 1 explains the weaving process. You should note that the original code doesn't need to know about any functionality the aspect has added; it needs only to be recompiled without the aspect to regain the original functionality.
Figure 1: Aspect Weaver
In that way, AOP complements object-oriented programming, not replacing it, by facilitating another type of modularity that pulls together the widespread implementation of a crosscutting concern into a single unit. These units are termed aspects, hence the name aspect oriented programming.

Aspect Oriented Programming and Java

AOP is a concept, so it is not bound to a specific programming language. In fact, it can help with the shortcomings of all languages (not only OO languages) that use single, hierarchical decomposition. AOP has been implemented in different languages (for example, C++, Smalltalk, C#, C, and Java).

AspectJ, created at Xerox PARC, was proposed as an extension of the Java language for AOP. The below topic is related to AspectJ terminology.

Join points, Pointcut, Advice, and Introduction

Where the tools of OOP are inheritance, encapsulation, and polymorphism, the components of AOP are join points, pointcut, advice, and introduction. For a better understanding of these new terms, let's consider the following simple example.
public class TestClass {
  public void sayHello () {
    System.out.println ("Hello, AOP");
  }

  public void sayAnyThing (String s) {
    System.out.println (s);
  }

  public static void main (String[] args) {
    sayHello ();
    sayAnyThing ("ok");
  }
}
Listing 1: TestClass.java
Now, we have our existing Java code in TestClass.java. Let's assume that we want to use aspects to do the following modifications:
  1. We would like to print a message before and after any call to the TestClass.sayHello() method.
  2. We need to test that the argument of the TestClass.sayAnyThing() method is at least three characters.
The following list is the AspectJ implementation.
1: public aspect MyAspect {
2:   public pointcut sayMethodCall (): call (public void
                                             TestClass.say*() );
3:   public pointcut sayMethodCallArg (String str): call
                     (public void TestClass.sayAnyThing (String))
                     && args(str);

4:   before(): sayMethodCall() {
5:   System.out.println("\n TestClass." +
       thisJoinPointStaticPart.getSignature().getName() +
       "start..." );
6:   }

7:   after(): sayMethodCall() {
8:   System.out.println("\n TestClass." +
       thisJoinPointStaticPart.getSignature().getName() +
       " end...");
9:   }

10:   before(String str): sayMethodCallArg(str) {
11:     if (str .length() < 3) {
12:     System.out.println ("Error: I can't say words less than 3
                             characters");
13:     return;
14:     }
15:   }
16: }
Listing 2: MyAspect.aj
Line 1 defines an aspect in the same way we define a Java class. Like any Java class, an aspect may have member variables and methods. In addition, it may include pointcuts, advices, and introductions.

In Lines 2 and 3, we specify where in the TestClass code our modification will take place. In AspectJ terms, we define two pointcuts. To explain what a pointcut means, we first need to define join points.

Join points represent well-defined points in a program's execution. Typical join points in AspectJ include method/constructor calls, method/constructor execution, field get and set, exception handler execution, and static and dynamic initialization. In our example, we have two join points: the call to TestClass.sayHello and TestClass.sayAnyThing methods.

Pointcut is a language construct that picks out a set of join points based on defined criteria. The criteria can be explicit function names, or function names specified by wildcards.
public pointcut sayMethodCall (): call (public void  TestClass.say*() );
In the preceding line, we define a pointcut, named sayMethodCall, that picks out any call to the TestClass.sayHello method. Moreover, it picks out any public TestClass method with zero arguments and a name that starts with "say" (for example, TestClass.sayBye).
Pointcuts are used in the definition of advice. An advice in AspectJ is used to define additional code to be executed before, after, or around join points. In our example, Lines 4–6 and 7–9 define two advices that will be executed before and after the first pointcut. Finally, Lines 10–15 implement an advice associated with the second pointcut and are used to set a precondition before the execution of the TestClass.sayAnyThing method.
Whereas pointcuts and advice let you affect the dynamic execution of a program, introduction allows aspects to modify the static structure of a program. By using introduction, aspects can add new methods and variables to a class, declare that a class implements an interface, or convert checked to unchecked exceptions. Introduction and a more practical application of AOP will be the subject of a future article.

AspectJ Compiler
Initially, you have to download the most recent version of AspectJ, available for free at its official site and install it. Compiling and running our example is very easy. Just write:

ajc MyAspect.aj TestClass.java java TestClass

You should note that the source code at TestClass.java didn't change. To return to the original functionality of your program, just use your Java compiler to re-compile it.