Presentation is loading. Please wait.

Presentation is loading. Please wait.

Spring Training 17/09/2007. 2 Dependency Injection.

Similar presentations


Presentation on theme: "Spring Training 17/09/2007. 2 Dependency Injection."— Presentation transcript:

1 Spring Training 17/09/2007

2 2 Dependency Injection

3 3 How Do Factories work? Factories solve a common problem in software engineering: hiding the complexity of creating and configuring objects. example of a factory object in the Java SDK is the javax.net.SocketFactory class The Spring Framework Core Container supports both factory methods and factory objects as an alternative to creating new beans. javax.net.SocketFactory factory = javax.net.SocketFactory.getDefault(); java.net.Socket socket = factory.createSocket("localhost", 80);

4 4 Introducing the BeanFactory The Spring Framework Core Container is also a factory object with configuration parameters and factory operations to support IoC. The operations of the Core Container are defined in the org.springframework.beans.factory.BeanFactory interface

5 5 Setter injection and Constructor Injection

6 6 bean-config file

7 7 Test with JUnit

8 8 Constructor Overload Player Bean TestPlayer

9 9 Constructor Overload Player Bean TestPlayer

10 10 Combine Constructor and setter Player Bean TestPlayer FirstExample-1.zip

11 11 Setter or constructor ? Setter injection is more popular because it’s more self- documenting and isn’t affected by circular dependency problems, which may occur if you use constructor injection. Setter injection leaves beans in an indeterminate state, something you can avoid with constructor injection

12 12 Inner bean (anonymous) The container supports inner bean definition, also called anonymous bean definitions since they cannot be referenced by other bean definitions. Inner bean definitions are useful for making the configuration more readable and to avoid exposing beans that are used in only one place.

13 13 FirstExample-2.zip

14 14 The Element

15 15 The Element

16 16 The Element

17 17 The Element

18 18

19 19 The Elements

20 20 The Element

21 21 Bean life-cycle The container creates and configures a bean based on its bean definition, which provides a single point to configure the life cycle of the bean. Along with dependency injection, the container also provides life-cycle options that address the following Scope Initialization Destruction

22 22 Scope The scope of a bean defines the behavior of the container when a bean is requested, either via dependency injection or dependency lookup. By default, beans are singleton, which means they are created and configured once and stored in a cache. When a singleton bean is requested, the container returns the instance from the cache. Optionally, beans can be prototype, which means they are created and configured by the container on each request. When a prototype bean is requested, the container creates and configures a new bean and doesn’t keep track of it.

23 23 Initialization The initialization of beans is available for singleton and prototype beans. The container can invoke a method on a bean if it implements a specific interface that is part of the Spring Framework API or if a custom initialization method has been configured on the bean definition. This is an optional step in the life cycle of a bean.

24 24 Destruction The destruction of beans is available only for singleton beans. The container can invoke a method on a bean if it implements a specific interface that is part of the Spring Framework API or if a custom destroy method has been configured on the bean definition. This is an optional step in the life cycle of a singleton bean.

25 25 Singleton Without extra configuration on the bean definition, beans are singleton A singleton bean may be used by multiple threads running concurrently, meaning its operations must be implemented in a thread-safe way. The execution of the bean life-cycle process by the container is guaranteed to be thread-safe, so operations that are executed during this process are not subject to thread-safety issues. Once the life-cycle process of the container is over, all operations that are allowed on singleton beans must happen in a thread-safe way. By default, the BeanFactory will not preinstantiate singletons, but will instead create each singleton bean when it’s first requested PrimeNumber-1.zip

26 26 Using prototypes Prototype beans typically have internal state that is related to a single execution of a business process. Every execution of the business process requires a new bean, and executions that run concurrently cannot share the same bean. To configure a bean definition as a prototype, set the singleton attribute of the element to false

27 27 the BeanFactory will not preinstantiate singletons, but will instead create each singleton bean when it’s first requested In contrast, the ApplicationContext will preinstantiate singleton beans Prototype beans are not preinstantiated by the BeanFactory or ApplicationContext container

28 28 Bean Initialization The container can optionally initialize beans, either via an interface that is implemented by beans or via a custom initialization method Initialization step can be used to check the internal state of beans The container will initialize any bean that implements the org.springframework.beans.factory.InitializingBean interface

29 29 Initialize via interface SecondExample-1.zip

30 30 Using Custom Initialization Methods

31 31 Using Custom Initialization Methods The init-method attribute takes the method name of the custom initialization method. The container requires that custom initialization methods have no arguments. They can throw exceptions that are handled in the same way as those thrown by the afterPropertiesSet() method and can return values, but these are ignored by the container. We recommend that you use the custom initialization method strategy as much as possible, since it avoids coupling application code to the Spring Framework API.

32 32 Bean Destruction Prototype objects are created by the container, returned, and forgotten about. The container does not keep track of prototype beans. The life cycle is restarted for a prototype every time a new object is created. In contrast, singleton instances are stored in a cache and can be destroyed when the container is closed. The destruction step is useful for cleaning up resources when the application stops. Just like the initialization step, the destruction step can be configured in two ways: through an interface that is implemented by beans or through a custom destruction method.

33 33 Using the DisposableBean Interface Does not require special configuration, as the container will recognize that the class implements the DisposableBean interface SecondExample-2.zip

34 34 Using a Custom Destroy Method PrimeNumber-2.zip

35 35 Using Factory Methods and Factory Objects in the Container Factories that come in two forms: factory methods and factory objects. The container supports both factory types as an alternative to creating new beans. The products of factories are used by the container as beans, which means the container must know how to get objects from the factories. The beans that are returned by factory methods and factory object methods go through the entire bean life cycle Singleton/prototype configuration Setter injections Initialization methods Destroy methods, if configured as singleton When the factory object bean definition is configured as a prototype, each bean definition that calls one of its methods will trigger the creation of a new factory object bean that will be used only for that method invocation

36 36 Implementing Factory Methods Factories-1.zip

37 37 Implementing Factory Objects Factories-1.zip

38 38 PropertyEditor The bean factory uses PropertyEditors for converting the String values in XML files to the destination type of properties and constructor arguments. The java.beans.PropertyEditor interface, which is part of the Java Software Development Kit (SDK), handles the conversion of Strings to a specific type and back. PropertyEditor.zip

39 39 ApplicationContext The ApplicationContext interface inherits all the capabilities of the BeanFactory interface, including dependency lookup, dependency injection, and support for factories and PropertyEditors. The ApplicationContext automates functionalities that are offered by BeanFactory; for example, it automatically preinstantiates singletons and automatically detects beans that implement specific interfaces in the container. The most commonly used feature of the ApplicationContext is its generic representation of resources. Resources can reside on the file system ( file:wordlist.txt ), in the classpath ( classpath:wordlist.txt ), on a web server accessible through a URL ( http://localhost/wordlist.txt ), or inside a deployed WAR application

40 40 Representing Resources A resource location without a prefix will be loaded from the default location, which depends on the type of ApplicationContext being used There are three possible types: ClassPathXmlApplicationContext : Reads resources from the classpath by default. FileSystemXmlApplicationContext : Reads resources from the file system by default. XmlWebApplicationContext : Reads resources from the ServletContext object by default. Every time you set a bean property that has the org.springframework.core.io.Resource interface as its type, you can specify a string location that will be converted by the ApplicationContext

41 41 Creating ApplicationContext Objects The three most common ways of creating ApplicationContext objects are as follows: Creating an ApplicationContext in Java code Creating an ApplicationContext in an integration test Creating an ApplicationContext in a web application The ApplicationContext allows you to load multiple XML files that will be merged into a set of bean definitions You should configure the modules of your applications in separate configuration files and load them together in one ApplicationContext. This will keep your configuration files small enough to manage conveniently.

42 42 Using the Container As a Deployment Model The Spring Framework offers support to deploy applications in these deployment environments: Servlet containers: Tomcat, Jetty, and Resin Application servers: BEA WebLogic, IBM WebSphere, and JBoss Portlet servers: JetSpeed 2 and Pluto Thin clients: Java desktop applications that call remote services over a network Thick clients: Java desktop applications that directly connect to a database Messaging: Applications that connect to message queues and handle incoming messages

43 43 AOP Any functionality that exists in an application, but cannot be added in a desirable way is called a cross-cutting concern The field in computer science that deals with cross-cutting concerns is called aspect-oriented programming (AOP) It deals with the functionality in applications that cannot be efficiently implemented with pure object-oriented techniques.

44 44 Implementing Cross-Cutting Concerns Advice In AOP jargon, the implementation of a cross-cutting concern is called an advice. The advice class is written and compiled once—it’s a regular Java class—and can be reused many times, meaning it needs to be tested only once. Proxy object Proxy objects are created at runtime by ProxyFactoryBean ; you don’t need to write any code to create them. All public methods on the target object are available on the proxy object, and you can decorate any of these methods with advice. Spring AOP supports two proxy types: Java Development Kit (JDK) proxies –specify interface names in the ProxyFactoryBean configuration Bytecode proxies –protected methods on target objects can be called on proxy objects in Spring AOP 2.0, and these methods can be decorated with advice. –final classes and methods cannot be proxied, which is the sole limitation of bytecode-generated proxy objects.

45 45 JDK proxy Sales-1.zip

46 46 Seller

47 47 textMessageSendAdvice

48 48 newSale

49 49 messageSender

50 50 Bytecode proxy Sales-2.zip

51 51 Filtering Methods AOP frameworks allow you to define which advice is applied to which methods Specifying the advice and method involves using what AOP terms join points and pointcuts Spring AOP supports only method invocations as join points. A pointcut selects zero or more join points on the target object

52 52 Point cut classes Spring AOP has a number of pointcut classes you can use to select join points: org.springframwork.aop.support.NameMatchMethodPointcut: Selects join points based on method names. This class matches method names using an Ant-style wildcard notation org.springframwork.aop.support.JdkRegexpMethodPointcut: Selects join points based on method names. This class matches method names using regular expressions and works only with Java 1.4 and newer because it uses the java.util.regexp package. org.springframwork.aop.support.Perl5RegexpMethodPointcut: Selects join points based on method names. This class matches method names using regular expressions and uses the Jakarta ORO open source regular expression library; thus, it supports Java 1.3. When using the regular expression–based pointcut classes to match method names, the package name, class name, or method name can be matched, offering a more powerful selection mechanism.

53 53 NameMatchMethodPointcut Sales-3.zip

54 54 JdkRegexpMethodPointcut Here the pattern property has been set to a regular expression that should match any method called getSale() on any class. Sales-4.zip

55 55 Adding Advisors Pointcuts select zero or more join points You need to use them in combination with an advice to define to which methods the advice applies An advisor takes a pointcut and an advice object and is passed to ProxyFactoryBean Methods on proxy objects can have more than one advisor assigned to them. In this case, the order of execution is defined by the order in the XML configuration file To control the proper ordering of multiple advisors, Spring AOP uses an advisor chain to execute all configured advisors sequentially.

56 56 Using PointcutAdvisors Spring AOP provides convenience classes for the pointcut classes. These classes turn pointcut classes into advisors. Three classes are available: org.springframework.aop.support.NameMatchMethodPointcutAdvisor org.springframework.aop.support.JdkRegExpMethodPointcutAdvisor org.springframework.aop.support.Perl5RegExpMethodPointcutAdvisor These convenience classes inherit the properties defined in the pointcut class they extend and add the advice property You should use these classes instead of a separate pointcut and an advisor class to reduce the number of lines in the XML configuration files

57 57 NameMatchMethodPointcutAdvisor So, what happens when an advice is passed to ProxyFactoryBean without an advisor? Spring AOP uses an advisor for the advice that matches all methods on the target object. As a result, an advice that is configured without an advisor will be applied to all methods of the target object Sales-5.zip

58 58 Selecting Advice Types 1. Around advice: Controls the execution of a join point. This type is ideal for advice that needs to control the execution of the method on the target object. 2. Before advice: This Is executed before the execution of a join point. This type is ideal for advice that needs to performan action before the execution of the method on the target object. 3. After advice: This Is executed after the execution of a join point. This type is ideal for advice that needs to perform an action after the execution of the method on the target object. 4. Throws advice: This Is executed after the execution of a join point if an exception is thrown. This type is ideal for advice that needs to performan action when the execution of the method on the target object has thrown an exception.

59 59 Around Advice (Method interceptor) The around advice type (also called a method interceptor) controls the flow of method invocations on target objects. This advice type is ideal for cross-cutting concerns that need to control the method invocation. It is called before the method on the target object is executed and exits after this method returns. Around advice classes can access the arguments passed to the method on the proxy object by calling the MethodInvocation.getArguments() method

60 60 Method interceptor definition Sales-6.zip

61 61 Simple profiling class of MethodInterceptor The advice implementation is responsible for continuing the interceptor chain by calling the proceed(). When the proceed() method is called, any additional advice is executed, before the method on the target object is executed.

62 62 Before Advice Before advice is ideal for actions that must occur before a method on a target object is called. It is called before the target method is invoked and can interrupt the invocation only by throwing an exception. implement the org.springframework.aop.MethodBeforeAdvice interface to create before advice

63 63 Check arguments are not null before execute Sales-7.zip

64 64

65 65 After Advice After advice will be not executed if the target method throws an exception This advice type is ideal for actions that need access to the value returned by the target method and otherwise do not need to control the execution of the target method After advice cannot interrupt the execution of the method on the target object, since it’s called after that This advice type can interrupt the further invocation of the advisor chain by throwing an unchecked exception ( java.lang.RuntimeException or java.lang.Error ) or a checked exception that is declared in the signature of the method on the proxy object

66 66 Throws Advice Throws advice is called when the method execution on the target object throws a specific exception type This advice type is ideal for actions that need access to exceptions or otherwise need control when specific exception types are thrown Throws advice does not control the method execution because it’s called after exceptions are thrown

67 67 ThrowsAdvice is probably the strangest interface that is part of the Spring Framework, since it doesn’t define any methods and yet must be implemented by advice classes. Instead of defining methods in the interface, Spring AOP recognizes and supports magic methods in classes that implement this interface The magic methods for throws advice supported by Spring AOP need to be named afterThrowing().

68 68 These methods must have either of the two method signatures. Spring AOP will call the most specific afterThrowing() method defined in throws advice, which is the method with an exception argument type that’s type-compatible with the actual type that is thrown and closest to it in the class hierarchy.

69 69 Throwing Exceptions with Spring AOP Advice Each of the Spring AOP advice interfaces discussed allows you to throw exceptions. When an exception is thrown from an advice, one of three things happens: Unchecked exceptions are passed to any other advice in the advisor chain and eventually to the caller. Checked exceptions that are declared in the method signature of the target method are also passed to any other advice in the advisor chain and eventually to the caller. Checked exceptions that are not declared in the method signature of the target method will be wrapped in java.lang.reflect.UndeclaredThrowableException, which is unchecked.

70 70 Many of the services offered by the Spring Framework use the Spring AOP framework internally. Each service typically has one or more ProxyFactoryBean classes to simplify the AOP configuration. These include the following: Transaction management: Remote access

71 71

72 72 USA INDIA SRI LANKA UK www.virtusa.com © V I r t u s a C o r p o r a t i o n "Virtusa" is a trademark of the company and a registered trademark in the EU and In India. "Productization" is a service mark of the company and a registered service mark in the United States. "vRule" is a service mark of the company. For more information please contact SalesInquiries@virtusa.com


Download ppt "Spring Training 17/09/2007. 2 Dependency Injection."

Similar presentations


Ads by Google