Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
Agenda
Bean Life Cycle Bean Scoping Autowiring Parent-Child Beans Injecting Non-Spring Beans Externalizing Configuration Properties Annotation based dependency injection
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
Populating Properties
o Constructor Injection o 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
Wiring Collections
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.
Wire the above dependencies using Springs dependency injection and start the container.
Solution: Refer com.sapient.wiring package
10
11
12
Implement setBeanFactory method. Beans can look up collaborating beans via the factory.
13
Usage: Access to parameterized text message in a message source. Publish application events.
14
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.
15
Initializing Bean
Bean needs to implement InitializingBean interface. Usage: Perform some initialization to get the bean into a usable state.
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
16
Initializing Bean
init-method is an attribute in bean element. Advantages: Purpose same as InitializingBean except bean has no dependency on Spring class.
17
18
19
20
21
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
23
24
25
Inner Beans
Self Study Inner Beans
o Anonymous bean configuration inside another bean configuration.
26
Instantiate a FoodFactory class to return the FoodProduct object. (factory instance implementation)
27
Autowiring
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:
29
Autowiring | byName
Name of the property matches with the name of the bean that is to be wired.
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
Limitations:
o Exception thrown if Spring finds more than one bean whose type is assignable to autowired property.
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.
32
Self Study
o autodetect autowiring o default-autowire attribute in the beans element in spring configuration
33
34
Parent-Child Beans
35
36
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
Overriding a property allowed. Parent bean does not have to be abstract. Possible to subclass a concrete bean.
38
Define CardAuthorizerImpl, CreditCardAuthorizerImpl and DebitCardAuthorizerImpl Spring config xml and set them through inheritance.
beans in
39
40
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.
41
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.
42
43
44
45
PropertyPlaceholderConfigurer
o Pulls values from properties file into bean definitions.
46
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
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.
49
50
51
P-Namespace
52
Util Schema
<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.
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
54
55
56
@Autowired
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.
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
59
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
60
61
62
Inner Beans
o Use when bean only available to a parent bean
63
Best Practices
64
Appendix - A
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.
66
Thank You!
COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL
67