Tuesday, May 10, 2011

Spring Aop

  1. Spring AOP
  2. OO Design is good but…
    • The oop languages makes the code design more reusable and compact.
    • But sometimes it makes the code scattered in number of modules.
    • More code plumbing has to be done…
    • Example : adding message logging in each of class methods makes the logging code scattered in number of methods and classes.
    • This makes code maintenance and updation a tedious work.
  3. AOP is the solution…
    • ‘ Aspect Oriented Programming(AOP)’ addresses these issues.
    • Instead of adding the logging code in each of the methods, you delegate the logging functionality ( concern ) across number of methods to an aop container and specify which methods require logging applied.
    • The container will call the logging aspect of the code when the methods are invoked on the proxy object returned by the Container.
  4. AOP
    • Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. In addition to classes, AOP gives you aspects .
    • Aspects enable modularization of concerns (required additional business logic) such as transaction management that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns.)
  5. AOP In JSP Engine Register.jsp (throws Exception) Login.jsp (throws SQLException) Update.jsp (throws UserException) request request request Handler.jsp <%=exception%> <%@page errorPage=“Handler.jsp”%> <%@page errorPage=“Handler.jsp”%> <%@page errorPage=“Handler.jsp”%> <%@page isErrorPage=“true”%> JSP Engine
  6. We are using AOP…
    • For exception handling in the JSP pages,instead of writing individual ‘try-catch’ blocks in each jsp we make a common exception handler jsp and specify in each jsp the ref. of this common handler by using isErrorPage and errorPage attributes in page directive tag.
    • When any of the jsp page generates the exception it is forwarded to common handler page by the web container.
    • Another example is specifying Filters to be invoked transparently before Servlet invocations in java web applications.
  7. AOP advantages
    • Complements OO programming.
    • Clean and modular code without additional code plumbing.
    • Aspects can be added or removed as needed without changing the code.
    • The business object code is not tied to specific API or framework
  8. Some AOP terminologies
    • Concern - The required functionality.(logging,tracing etc.)
    • Aspect – A modularization of a concern that cuts across multiple objects and methods.
    • Join point – A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
    • Advice – the block of code that runs based on the pointcut definition
  9. AOP Terminologies
    • Pointcut – A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name).
    • Advisor - references the advice and the pointcut.
    • Target object : Object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
    • AOP proxy : An object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on).
  10. More aop terms..
    • Introduction : Declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any proxied object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching.
    • Weaving – Linking aspects with other application types or objects to create an advised object can be done at runtime or compile time. Which inserts the advice (crosscutting concerns) into the code. Spring provides run time weaving.
  11. Cross cutting concerns
    • Concerns applied across number of classes are called as cross cutting concerns.
  12. Spring AOP support
    • AOP Framework that builds on the aopalliance interfaces.
    • Aspects are coded with pure Java code.
    • Spring aspects can be configured using its own IoC container.
      • Objects obtained from the IoC container can be transparently advised based on configuration
    • Spring AOP has built in aspects such as providing transaction management, performance monitoring and more for your beans.
    • Spring supports proxy based AOP to bean methods.
  13. Spring Advices
    • Spring AOP supports the following advices:
      • Before advice : (Advice is applied before method is executed)
      • After returning advice : (Advice is applied after method is returned normally without throwing any Exceptions)
      • After throwing advice : Advice to be executed if a method exits by throwing an exception.
      • Around advice : Advice that surrounds a join point such as a method invocation. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.
  14. Simple AOP Weaving
  15. Applying the Advices..
    • Aspects are weaved together at runtime. AspectJ uses compile time weaving.
    • Spring AOP also includes advisors that contain advice and pointcut filtering.
    • IoC + AOP is a great combination that Makes the code non-invasive
  16. Using Spring AOP
    • To provide declarative enterprise services, especially as a replacement for EJB declarative services such as declarative transaction management .
    • Providing declarative linking of web application components.
    • To allow users to implement custom aspects, complementing their use of OOP with AOP.
  17. Spring AOP Features
    • Spring AOP does not need to control the class loader hierarchy, and is thus suitable for use in a J2EE web container or application server or in a desktop application.
    • Spring AOP currently supports only method execution join points.
    • The aspects can be programmatically or declaratively configured through xml.
    • The aspects can be configured with jdk1.5 annotations features.
  18. Method Interceptor
    • MethodInterceptor used to implement for Advices/Interceptors on methods.
      • public Object invoke(MethodInvocation invocation) throws Throwable
  19. Spring Advice interfaces
    • BeforeAdvice
      • Public void before(Method m, Object[] args, Object target) throws Throwable;
    • ThrowsAdvice
      • public void afterThrowing(Method m, Object[ ] args, Object target, Throwable ex);
    • AfterReturningAdvice
      • Public void afterReturning(Object returnValue, Method m, Object[ ] args, Object target) throws Throwable;
  20. Defining PointCut
    • package org.springframework.aop;
    • public interface Pointcut
    • {
    • ClassFilter getClassFilter();
    • MethodMatcher getMethodMatcher();
    • }
  21. ClassFilter
    • Public boolean matches ( Class  clazz);
    • Decides whether the specified pointcut should be applied to the given interface or target class objects.
    • Filter that restricts matching of a pointcut or introduction to a given set of target classes.
    • Can be used as part of a pointcut, or for the entire targeting of an IntroductionAdvice
  22. MethodMatcher
    • Part of a Pointcut. Checks whether the target method is eligible for advice.
    • A MethodMatcher may be evaluated statically or at runtime (dynamically).
    • Static matching involves method and (possibly) method attributes. Dynamic matching also makes arguments for a particular call available, and any effects of running previous advice applying to the joinpoint
  23. Apply MethodMatcher
    • If an implementation class returns false in its isRuntime() method, evaluation can be performed statically, and the result will be the same for all invocations of this method, whatever their arguments.
    • If the isRuntime() method returns false, the 3-arg matches() method will never be invoked.
  24. PointCut Usage
    • Used to target advices to particular classes and methods.
    • Spring's pointcut model enables pointcut reuse independent of advice types.
    • It's possible to target different advices using the same pointcut.
    • ClassFilter and MethodMatcher are interfaces which are used to restrict the pointcut to a given set of target classes and used to test matching of a particular method against a given method, respectively.
  25. Operations on pointcuts
    • Spring supports two operations on pointcuts:
      • Union means the methods that either pointcut matches and is usually more useful.
      • Intersection means the methods that both pointcuts match.
    • Pointcuts can be composed using the static methods in the org.springframework.aop.support.Pointcuts class, or using the ComposablePointcut class in the same package.
  26. Static pointcuts
    • Static pointcuts are based on method and target class, and cannot take into account the method's arguments.
    • Static pointcuts are sufficient for most usage. It's possible for Spring to evaluate a static pointcut only once, when a method is first invoked: after that, there is no need to evaluate the pointcut again with each method invocation.
  27. Dynamic pointcuts
    • These take into account method arguments , as well as static information. This means that they must be evaluated with every method invocation and the result cannot be cached, as arguments will vary.
    • Example is the control flow pointcut.
    • Control flow pointcuts are specified using the ControlFlowPointcut class.
    • Spring provides useful pointcut super classes to help you to implement your own pointcuts.
  28. Spring Advisor
    • Spring has defined Advisor interface for combining advice and pointcut.
    • This is the base interface holding AOP advice (action to take at a joinpoint) and a filter determining the applicability of the advice (such as a pointcut).
    • This allows for common support for different types of advices.
    • Spring AOP is based around around advice delivered via method interception, compliant with the AOP Alliance interception API.
    • The Advisor interface allows support for different types of advice, such as before and after advice, which need not be implemented using interception.
  29. Advisor Implementation
    • Spring has a RegexpMethodPointcutAdvisor , that allows us to also reference an Advice (Advice can be an interceptor, before advice, throws advice etc.)
    • This advice is mapped to specific matching methods.
    • DefaultIntroductionAdvisor applies by default to any class.
    • DefaultPointcutAdvisor :can be used with any pointcut and advice type, except for introductions.
    • DynamicMethodMatcherPointcutAdvisor : super class for classes as Advisors that are also dynamic pointcuts.
    • NameMatchMethodPointcutAdvisor :class for name-match method pointcuts that hold an Advice, making them an Advisor.
    • StaticMethodMatcherPointcutAdvisor :superclass for Advisors that are also static pointcuts.
  30. Advisor declaration
    • <bean id=“tg“
    • class=&quot;org..aop.support. RegexpMethodPointcutAdvisor &quot;>
    • <property name=&quot;advice&quot;>
    • <ref local=&quot;beanAdvice&quot;/>
    • </property>
    • <property name=&quot;patterns&quot;>
      • <list>
      • <value>.*set.*</value>
      • <value>.*Calculate</value>
      • </list>
    • </property>
    • </bean>
  31. Spring PointCut Classes
    • ComposablePointcut : class for building up pointcuts.
    • ControlFlowPointcut :Pointcut and method matcher for use in simple cflow-style pointcut.
    • DynamicMethodMatcherPointcut :Base class when we want to force subclasses to implement MethodMatcher interface, but subclasses will want to be pointcuts. The getClassFilter() method can be overriden to customize ClassFilter behaviour as well.
    • StaticMethodMatcherPointcut : superclass when we want to force subclasses to implement the MethodMatcher interface, but subclasses will want to be pointcuts.

About Spring

(1) What is IOC (or Dependency Injection)?

The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.

i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.


(2) What are the benefits of IOC (Dependency Injection)?
  • Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
  • Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
  • Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
  • IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

(3) What is Bean Factory ?


A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
  • BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.
  • BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
(4) What is Application Context?


A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
  • A means for resolving text messages, including support for internationalization.
  • A generic way to load file resources.
  • Events to beans that are registered as listeners.
(5) What is the difference between Bean Factory and Application Context ?

On the surface, an application context is same as a bean factory. But application context offers much more..
  • Application contexts provide a means for resolving text messages, including support for i18n of those messages.
  • Application contexts provide a generic way to load file resources, such as images.
  • Application contexts can publish events to beans that are registered as listeners.
  • Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
  • ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
  • MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable
(6) What are the common implementations of the Application Context ?

The three commonly used implementation of 'Application Context' are
  • ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code .

  • ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
  • FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code .

  • ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
  • XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
(7) How is a typical spring implementation look like ?

For a typical Spring Application we need the following files:
  • An interface that defines the functions.

  • An Implementation that contains properties, its setter and getter methods, functions etc.,

  • Spring AOP (Aspect Oriented Programming)

  • A XML file called Spring configuration file.

  • Client program that uses the function.

(8) What is the typical Bean life cycle in Spring Bean Factory Container ?

Bean life cycle in Spring Bean Factory Container is as follows:

  • The spring container finds the bean’s definition from the XML file and instantiates the bean.

  • Using the dependency injection, spring populates all of the properties as specified in the bean definition

  • If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.

  • If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.

  • If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.

  • If an init-method is specified for the bean, it will be called.

  • Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

(9) What do you mean by Bean wiring ?

The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring.

(10) What do you mean by Auto Wiring?

The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes.

  • no

  • byName

  • byType

  • constructor

  • autodirect



(11) What is DelegatingVariableResolver?

Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard Java Server Faces managed beans mechanism which lets you use JSF and Spring together. This variable resolver is called as DelegatingVariableResolver

(12) How to integrate Java Server Faces (JSF) with Spring?

JSF and Spring do share some of the same features, most noticeably in the area of IOC services. By declaring JSF managed-beans in the faces-config.xml configuration file, you allow the FacesServlet to instantiate that bean at startup. Your JSF pages have access to these beans and all of their properties.We can integrate JSF and Spring in two ways:

  • DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you use JSF and Spring together.
  •                         org.springframework.web.jsf.DelegatingVariableResolver             

    The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and then to Spring's 'business context' WebApplicationContext. This allows one to easily inject dependencies into one's JSF-managed beans.

  • FacesContextUtils:custom VariableResolver works well when mapping one's properties to beans in faces-config.xml, but at times one may need to grab a bean explicitly. The FacesContextUtils class makes this easy. It is similar to WebApplicationContextUtils, except that it takes a FacesContext parameter rather than a ServletContext parameter.
  • ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()); 






    12 BENEFITS of Spring MVC over Struts

    1. Spring provides a very clean division between controllers, JavaBean models, and views.

    2. Spring’s MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.

    3. Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.

    4. Spring MVC is truly view-agnostic. You don’t get pushed to use JSP if you don’t want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism - for example, your own templating language - you can easily implement the Spring View interface to integrate it.

    5. Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.

    6. Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.

    7. The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.

    8. No ActionForms. Bind directly to domain objects

    9. More testable code (validation has no dependency on Servlet API)

    10. Struts imposes dependencies on your Controllers (they must extend a Struts class), Spring doesn’t force you to do this although there are convenience Controller implementations that you can choose to extend.

    11. Spring has a well defined interface to business layer

    12. Spring offers better integration with view technologies other than JSP (Velocity / XSLT / FreeMarker / XL etc.)

    Friday, November 26, 2010

    How To Cluster SpringSource tc Server | Javalobby

    How To Cluster SpringSource tc Server | Javalobby: "mvn archetype:create -DgroupId=com.test -DartifactId=ct-web -DarchetypeArtifactId=maven-archetype-webapp

    - Sent using Google Toolbar"