Sie sind auf Seite 1von 67

Spring202 Bean Wiring

23-Sep-2011

Prerequisites

Why Spring? Spring benefits Spring architecture Dependency Injection Spring Container BeanFactory and ApplicationContext Defining beans in the configuration file Explicit Bean Wiring Setter and Constructor based Injection

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

Agenda

Bean Life Cycle Bean Scoping Autowiring Parent-Child Beans Injecting Non-Spring Beans Externalizing Configuration Properties Annotation based dependency injection

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

Let us revise

Why Spring? Dependency Injection Spring Container BeanFactory and ApplicationContext Defining beans in the configuration file Explicit Bean Wiring Setter and Constructor based Injection

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

Spring Bean Lifecycle

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

Spring bean Lifecycle

Steps a bean goes through within Spring container

Called only if the bean is instantiated within ApplicationContext container.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

Bean Instantiation and Populating Properties



Let us revise (if not done already) Bean Instantiation
o BeanFactory Lazily Loaded o ApplicationContext Preloaded

Populating Properties
o Constructor Injection o Setter Method Injection

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

Constructor Injection vs. Setter Method Injection


Constructor Injection Setter Method Injection

Enforces the objects to be created with some state initialized. Enforces strong dependency contract. No need for superfluous setter methods. Helps in making the properties immutable.

Amenable to reconfiguration. If several dependencies, constructors parameter list can be quite lengthy. Several ways of constructing valid objects Difficult to come up with unique constructors. Parameters to super() method need to be passed manually in beans constructor.

Usage: Constructor Database Connection (should be initialized before use). Setter Singleton, Abstract classes etc. Best Practice: No hard and fast rule. Constructor based injection - Use type attribute than index attribute

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

Wiring Collections

Four types of collection configuration elements:


o o o o <list> - Wiring a list of values, allowing duplicates. <set> - Wiring a set of values, ensuring no duplicates. <map> - Name-value pair where name and value can be of any type. <props> - Name-value pair where name and value are both strings.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

Exercise | Investment Portal | Wiring

PaisaControl.com is a famous investment portal and it offers many products like insurance, loans, deposits etc. to its customers. Design the order management system (OMS) component of this portal. OMS is responsible for accepting the order having order and payment details, authorizing the payment with credit card authorization class and then approving/rejecting the order.

Following classes need to be designed:


o o o o o o o Order (Attributes: orderId, productCode, itemName, amount) Payment (Attributes: cardNumber, userId, password) OrderManager (Attributes: CreditCardAuthorizer, Method: placeOrder(Order,Payment)) CreditCardAuthorizer (Method: authorize(cardNumber, userId, password)) CreditCardAuthorizerImpl (Implementation of the CreditCardAuthorizer) Spring-Context.xml (Bean Configuration) Main (Load the container)

Wire the above dependencies using Springs dependency injection and start the container.
Solution: Refer com.sapient.wiring package

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

10

Exercise | Investment Portal | Collection



Create a new class OrderBasket that stores the collection of orders. This orderBasket along with Payment details are passed to the Ordermanager. Following additional classes need to be designed:
o OrderBasket(Attributes: orderBasket: Map<String, Order>) o OrderManager (Method: placeOrder(OrderBasket,Payment)) o Main (Load the container)

Populate the orderBasket attribute in OrderBasket class through DI.

Solution: Refer com.sapient.collection package

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

11

Setting the bean name


Bean needs to implement BeanNameAware interface. Usage: Useful in debugging when a number of beans are instantiated using the same class with each configured in a different way. Limitations: Class becomes Spring interface dependant.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

12

Setting the bean factory name


Bean needs to implement BeanFactoryAware interface.

Implement setBeanFactory method. Beans can look up collaborating beans via the factory.

Usage: Required when singleton bean needs to use non-singleton bean.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

13

Setting the application context


Bean needs to implement ApplicationContextAware interface.

Similar to BeanFactoryAware but some additional methods.

Usage: Access to parameterized text message in a message source. Publish application events.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

14

Bean Post Processor


Bean needs to implement BeanPostProcessor interface.

Provides two callback methods


o Before initializing a bean (postProcessBeforeInitialization) o After initializing a bean (postProcessAfterInitialization)

Usage: Used to log, update, perform the validations on the bean members. Example Logging the pre-init and post-init values of fields annotated with Log. ApplicationContextAwareProcessor is a bean post processor.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

15

Initializing Bean
Bean needs to implement InitializingBean interface. Usage: Perform some initialization to get the bean into a usable state.

o E.g. Opening a file, Looking up DB connection etc.

Perform validations on the fields to make sure the valid values are set.
o E.g. Autowired properties may need to be validated.

Limitations:
o Bean dependant upon Spring class. Better Alternative: init-method

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

16

Initializing Bean

init-method is an attribute in bean element. Advantages: Purpose same as InitializingBean except bean has no dependency on Spring class.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

17

Other lifecycle Steps

Self Study the following bean lifecycle steps


o o o o o DisposableBean Destroy-method Default-init-method Default-destroy-method BeanFactoryPostProcessor

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

18

Exercise | Investment Portal | Lifecycle

Implement the following bean lifecycle steps in the portal classes:


o o o o o o BeanNameAware BeanFactoryAware ApplicationContextAware BeanPostProcessor InitializingBean Init-method

Solution: Refer com.sapient.lifecycle package

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

19

Bean Scoping, Factory Method & Inner Bean

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

20

Bean Scoping | Singleton



Single instance of the bean is created in the container. By default, all spring beans are singleton (per application context).

Usage: Stateless beans are always made Singleton.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

21

Bean Scoping | Prototype


Creation of a new bean instance every time a request for that specific bean is made. Usage: Stateful beans are made Prototype.

Other scopes - request, session, global-session (only valid when used within a web-capable spring or portlet context. Covered in detail later)
COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

22

Bean Scoping | Prototype (Contd..)


Best Practice: Non-Singleton Beans (Prototype Beans)
o Avoid or design carefully if uses resources like database, network connection etc. o Similar to creating new objects in Java. o Useful for factory bean to create new bean instances or when a new object is required per request.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

23

Bean creation from factory methods



Calling factory method to get bean instance. Factory method has to be static.

Usage: Instantiating Third-Party Singleton Classes (with constructors private)


o Java.lang.RunTime o Java.awt.GraphicEnvironment

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

24

Bean creation from instance factory method

Instance Factory method Factory method non-static

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

25

Inner Beans

Self Study Inner Beans
o Anonymous bean configuration inside another bean configuration.

Link: Spring Inner Bean

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

26

Exercise | Investment Portal | Scope & Factory Method

Implement the following in the portal classes:


o Make the Order bean with scope Prototype. o Create a LogFactory singleton class and call its getInstance method to instantiate a bean.

Instantiate a FoodFactory class to return the FoodProduct object. (factory instance implementation)

Solution: Refer com.sapient.scoping package

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

27

Autowiring

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

28

Autowiring

Container determines how to wire a beans properties. If matching bean not found, property remains unwired.

Limitations: Hard to debug. Reduces XML code at the cost of readability. Either all attributes or none. (Only XML based Autowiring) Types:

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

29

Autowiring | byName

Name of the property matches with the name of the bean that is to be wired.

Autowiring and Explicit (Manual) wiring can be combined.


o Autowiring will try to wire the properties not wired through explicit wiring.

Limitations:
o Sometimes not possible to make the name of the target bean the same as the property. o If multiple orderManager defined then same creditCardAuthorizer instance will be wired. (if this is the requirement, then its not a limitation)
COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

30

Autowiring | byType

Spring finds out beans whose type is assignable to propertys type.

Limitations:
o Exception thrown if Spring finds more than one bean whose type is assignable to autowired property.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

31

Autowiring | constructor

Finds beans whose types satisfy the arguments of one of the constructor.

Limitations:
o Must wire all constructor arguments cant mix <constructor-arg> with constructor autowiring. o Exception thrown if Spring finds more than one bean whose type is assignable to a constructor parameter. o Exception thrown if dependencies of more than one constructor is satisfied by autowiring.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

32

Autowiring | Best Practices


Best Practices:

Avoid XML based autowiring


o Sacrifices the explicitness and maintainability of the configurations. o Hard to debug. o Prefer Annotation based autowiring (covered later) as it is easier to maintain and saves space and time.

Self Study
o autodetect autowiring o default-autowire attribute in the beans element in spring configuration

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

33

Exercise | Investment Portal | Autowiring

Wire the creditCardAuthorizer property of OrderManager class


o Use XML based autowiring. o Use byType, byName and constructor type to wire the above property.

Solution: Refer com.sapient.autowire package

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

34

Parent-Child Beans

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

35

Parent-Child Beans | constructor



Bean definitions in configuration xmls can show parent-child relationship. This cuts down redundant XML in context definition file. <bean> element provides two attributes:
o Parent Indicates the id of a bean which is the parent of the bean having the parent attribute. o Abstract If set to true, <bean> declaration is abstract and cant be instantiated by Spring.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

36

Abstracting a base bean type

Two beans with different ids but same class and properties.

The type(class) of all sub-beans is same as that of the parent bean. Overriding a property allowed. Parent bean does not have to be abstract. Possible to subclass a concrete bean.
COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

37

Abstracting common properties



Sub-beans dont have to share a common parent type. Two beans with different class attribute can just share the common set of attributes.

Overriding a property allowed. Parent bean does not have to be abstract. Possible to subclass a concrete bean.

Best Practice: Reuse bean definitions whenever possible.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

38

Exercise | Investment Portal | Inheritance

Write the following classes to implement Inheritance in Investment Portal


o o o o o Rename CreditCardAuthorizer interface to CardAuthorizer interface. CardAuthorizerImpl: Implements CardAuthorizerInterface CardAuthorizerImpl: Attribute: externalAuthorizerURL, userId, password. DebitCardAuthorizerImpl extends CardAuthorizerImpl CreditCardAuthorizerImpl extends CardAuthorizerImpl

Define CardAuthorizerImpl, CreditCardAuthorizerImpl and DebitCardAuthorizerImpl Spring config xml and set them through inheritance.

beans in

Solution: Refer com.sapient.inheritance package

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

39

Injecting non-spring beans

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

40

Injecting non-spring beans



Spring can also configure beans that it does not instantiate. Not all objects are instantiated by Spring.
o For ex. Domain objects by an ORM tool, custom tags by web container.

How to inject dependencies in non-spring beans?

Assume OrderManager is the bean instantiated outside the container scope. Set the bean attribute abstract=true o This means Spring container should not instantiate the bean instantiated outside the container.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

41

Injecting non-spring beans (Contd..)

Annotate the bean with @Configurable(<bean id>). This means o Bean configured by Spring though instantiated outside the container. o Associate the class with bean id passed as parameter.

Configuration to let Spring know that it needs to configure few beans instantiated outside the Spring container.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

42

Injecting non-spring beans (Contd..)

Starting Aspect-J enabled JVM by passing instrument jar file as VM argument.

Add the following jars in the classpath:


o Aspectjweaver.jar o Aspectjrt.jar o org.springframework.aspects-3.1.0.M2.jar

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

43

Exercise | Investment Portal | Non-Spring Beans



Implement the necessary changes to instantiate OrderManager class outside the scope of container. The property OrderManager.creditCardAuthorizer should be set through bean wiring.

Solution: Refer com.sapient.nonspring package

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

44

External Configuration Properties & Property Editors

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

45

Externalizing Configuration Properties

Application Specific Configurations vs. Deployment Specific Configurations


o Application Specific Spring Configuration. For ex. Inter-objects dependencies o Deployment Specific External properties file. For ex. Connection URL

PropertyPlaceholderConfigurer
o Pulls values from properties file into bean definitions.

Values in properties file


o <key>=<value> o For ex. oms.authorizeduser=xyz

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

46

Externalizing Configuration Properties

Syntax to fetch the properties


o ${placeholder-variable}

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

47

Internationalization

Display text in users native language. If resource bundle is oms
o oms.properties - Default o oms_en_US.properties English speaking people in US o oms_hi_IN.properties Hindi Speaking people in India

ResourceBundleMessageSource
o Id has to be messageSource

ApplicationContext.getMessage
o Parameters Message key, argument and locale

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

48

Property Editors

Wiring String value to non-String type or vice-versa. Simplifies bean wiring of some data types like java.io.File, java.util.Date, java.lang.class etc. Java.beans.PropertyEditorSupport
o getAsText() Returns String representation of a propertys value. o setAsText(String value) Sets a bean property value from the String value passed in.

Spring inbuilt PropertyEditors


o o o o o o FileEditor java.io.File URLEditor java.net.URL LocaleEditor java.util.Locale CustomDateEditor java.util.Date ClassEditor java.lang.Class StringArrayPropertyEditor Comma delimited String to String array.

o Custom PropertyEditors can also be written by extending Java.beans.PropertyEditorSupport class.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

49

Exercise | Investment Portal | External Config



Add a new attribute threadCount in OrderManager and read its value from oms.properties file present in the same package. Make the above threadCount locale dependant and read its local specific value from the properties file.

Solution: Refer com.sapient.externalconfig package

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

50

P namespace and util schema

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

51

P-Namespace

Shortcut for defining properties.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

52

Util Schema

Utility configuration issues


o Referencing constants o Configuring collections o Etc

<util:constant/>
o Set a constant value(e.g. 'java.sql.Connection.TRANSACTION_SERIALIZABLE) to a property value.

<util:property-path/>
o Creating a bean having the value equal to the x property of y bean.

<util:properties/>
o Instantiate java.util.Properties instance with the values loaded from Resource location.

<util:list/>
o Explicity control the exact type of list which will be instantiated.

Refer: com.sapient.beanwiring.util package


COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

53

Loading Resources

Reading External Resources (e.g. Text files, XML, Properties, Images etc) From Remote Locations (e.g. File system, classpath, URL) ApplicationContext.getResource Prefixes: file, classpath

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

54

Exercise | Util Schema



Write LoginDao and LogoutDao with the following properties LoginDao o isolationLevel Set the value java.sql.Connection.TRANSACTION_SERIALIZABLE o propertySet - java.util.Properties Populate the properties from jdbc.properties LogoutDao o isolationLevel Set the value LoginDao. isolationLevel o logoutPages logoutPages: List<String> - Populate set of three pages in the LinkedList

Solution: Refer com.sapient.util

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

55

Annotation based dependency injection

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

56

@Autowired

XML Based Wiring Limitations


o Wires all properties What if you like to wire a specific property only? o Only by type or name What if neither strategy suits you?

DI through Annotation is solution.


@Autowired and @Autowired (required=false) Autowiring by Type. Target Setters, Methods, Constructors, Attributes Registering AutowiredAnnotationBeanPostProcessor

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

57

@Qualifier

Specifying a candidate bean name when more than one bean with compatible type in container Target Fields, Parameters, Type, Annotation Type

Best Practice: Prefer Annotation based Autowiring over XML based. Add @Qualifier annotation wherever required to make the code more readable.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

58

Component Scanning
Limitation: Every bean declared manually in configuration file. What if Spring automatically detects the components?

Spring supports:
o o o o @Component Basic Annotation @Repository Components in Persistence Layer @Service Components in Service Layer @Controller Components in Presentation Layer

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

59

Component Scanning (Contd..)


Naming Convention: Default: Same as class name but the first alphabet in lowercase. Name: Bean name can be passed as parameter to annotations. For ex: @Service(<bean name>)

Scanning can be customized by applying include/exclude filters. Scanning Annotations not required if a class is defined in include-filter. Types
o o o o Annotation Annotation type Assignable - Class/Interface for filtering Regex Regular Expression Aspectj Pointcut expression matching the classes

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

60

Exercise | Investment Portal | Annotations



Modify the Spring configuration file to Autowire the property of OrderManager class through Annotation. Scan all the bean definitions in the given package than manually defining them in the config file.

Solution: Refer com.sapient.autowire.annotation

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

61

Additional Best Practices

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

62

Additional Best Practices

Prefer ApplicationContext over BeanFactory


o ApplicationContext supports i18n, Resource Loading and Events o BeanFactory preferred when there is limitation on resources and size of application. For ex. Applets, Mobile Applications.

Bean Naming Convention


o Use clear, descriptive naming convention for beans o Recommendation: CamelCase. o Use Java naming convention for classes with first alphabet in lowercase

Inner Beans
o Use when bean only available to a parent bean

Use <null/> or null property


o Leaving blank may set some other default values in the properties.

Split the configuration in different xml files.


o Minimal one xml file per architectural layer.

Prefer assembling beans (multiple xmls) through ApplicationContext over imports.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

63

Best Practices

Every bean must have an id or name.


o No anonymous bean. o Id attribute makes XML parsers validate the bean.

Update Config files(if required) after making Java changes.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

64

Appendix - A

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

65

Exercises | Solution
Steps to Import the solutions in Eclipse STS.

Open Spring Source Tool Suite. Select File->Import. Select General->Existing Projects into Workspace. Select the Select Archive File and open the attached zip. Click Finish.

COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

66

Thank You!
COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

67

Das könnte Ihnen auch gefallen