bean wiring - training prez new

Upload: promila-singh

Post on 05-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Bean Wiring - Training Prez New

    1/67

    Spring202 Bean Wiring23-Sep-2011

  • 7/31/2019 Bean Wiring - Training Prez New

    2/67

    2 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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

  • 7/31/2019 Bean Wiring - Training Prez New

    3/67

    3 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

  • 7/31/2019 Bean Wiring - Training Prez New

    4/67

    4 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

  • 7/31/2019 Bean Wiring - Training Prez New

    5/67

    5 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Spring Bean Lifecycle

  • 7/31/2019 Bean Wiring - Training Prez New

    6/67

    6 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.

  • 7/31/2019 Bean Wiring - Training Prez New

    7/677 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Bean Instantiation and Populating Properties

    Let us revise (if not done already)

    Bean Instantiationo BeanFactory Lazily Loaded

    o ApplicationContext Preloaded

    Populating Propertieso Constructor Injection

    o Setter Method Injection

  • 7/31/2019 Bean Wiring - Training Prez New

    8/678 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Constructor Injection vs. Setter Method Injection

    Constructor Injection

    Enforces the objects to be created with somestate initialized.

    Enforces strong dependency contract. No need for superfluous setter methods. Helps in making the properties immutable.

    Setter Method Injection

    Amenable to reconfiguration. If several dependencies, constructors

    parameter list can be quite lengthy. Several ways of constructing valid objects

    Difficult to come up with uniqueconstructors.

    Parameters to super() method need to be

    passed manually in beans constructor.

    Best Practice:

    No hard and fast rule. Constructor based injection - Use type attribute than indexattribute

    Usage:

    Constructor Database Connection (should be initialized before use).

    Setter Singleton, Abstract classes etc.

  • 7/31/2019 Bean Wiring - Training Prez New

    9/679 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Wiring Collections

    Four types of collection configuration elements:o - Wiring a list of values, allowing duplicates.

    o - Wiring a set of values, ensuring no duplicates.

    o - Name-value pair where name and value can be of any type.

    o - Name-value pair where name and value are both strings.

  • 7/31/2019 Bean Wiring - Training Prez New

    10/6710 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, authorizingthe payment with credit card authorization class and then approving/rejecting the order.

    Following classes need to be designed:o Order (Attributes: orderId, productCode, itemName, amount)

    o Payment (Attributes: cardNumber, userId, password)

    o OrderManager (Attributes: CreditCardAuthorizer, Method: placeOrder(Order,Payment))

    o CreditCardAuthorizer (Method: authorize(cardNumber, userId, password))

    o CreditCardAuthorizerImpl (Implementation of the CreditCardAuthorizer)

    o Spring-Context.xml (Bean Configuration)

    o Main (Load the container)

    Wire the above dependencies using Springs dependency injection and start the container.

    Solution: Refer com.sapient.wiring package

  • 7/31/2019 Bean Wiring - Training Prez New

    11/6711 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Exercise | Investment Portal | Collection

    Create a new class OrderBasket that stores the collection of orders. This orderBasket along withPayment details are passed to the Ordermanager.

    Following additional classes need to be designed:o OrderBasket(Attributes: orderBasket: Map)

    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

  • 7/31/2019 Bean Wiring - Training Prez New

    12/6712 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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 eachconfigured in a different way.

    Limitations:

    Class becomes Spring interface dependant.

  • 7/31/2019 Bean Wiring - Training Prez New

    13/6713 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Setting the bean factory name

    Bean needs to implement BeanFactoryAware interface.

    Implement setBeanFactorymethod. Beans can look up collaborating beans via the factory.

    Usage:

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

  • 7/31/2019 Bean Wiring - Training Prez New

    14/6714 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Setting the application context

    Bean needs to implementApplicationContextAware interface.

    Similar to BeanFactoryAware but some additional methods.

    Usage:

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

  • 7/31/2019 Bean Wiring - Training Prez New

    15/67

    15 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Bean Post Processor

    Bean needs to implement BeanPostProcessor interface.

    Provides two callback methodso 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.

  • 7/31/2019 Bean Wiring - Training Prez New

    16/67

  • 7/31/2019 Bean Wiring - Training Prez New

    17/67

    17 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Initializing Bean

    init-methodis an attribute in bean element.

    Advantages:

    Purpose same as InitializingBean except bean has no dependency on Spring class.

  • 7/31/2019 Bean Wiring - Training Prez New

    18/67

    18 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Other lifecycle Steps

    Self Study the following bean lifecycle stepso DisposableBean

    o Destroy-method

    o Default-init-method

    o Default-destroy-method

    o BeanFactoryPostProcessor

  • 7/31/2019 Bean Wiring - Training Prez New

    19/67

    19 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Exercise | Investment Portal | Lifecycle

    Implement the following bean lifecycle steps in the portal classes:o BeanNameAware

    o BeanFactoryAwareo ApplicationContextAware

    o BeanPostProcessor

    o InitializingBean

    o Init-method

    Solution: Refer com.sapient.lifecycle package

  • 7/31/2019 Bean Wiring - Training Prez New

    20/67

    20 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Bean Scoping, Factory Method & Inner Bean

  • 7/31/2019 Bean Wiring - Training Prez New

    21/67

    21 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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.

  • 7/31/2019 Bean Wiring - Training Prez New

    22/67

    22 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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-capablespring or portlet context. Covered in detail later)

  • 7/31/2019 Bean Wiring - Training Prez New

    23/67

    23 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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 newobjects in Java.

    o Useful for factory bean to create new bean instances or when a new object is required per request.

  • 7/31/2019 Bean Wiring - Training Prez New

    24/67

    24 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Bean creation fromfactorymethods

    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

  • 7/31/2019 Bean Wiring - Training Prez New

    25/67

    25 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Bean creation from instancefactorymethod

    Instance Factory method Factory method non-static

  • 7/31/2019 Bean Wiring - Training Prez New

    26/67

    26 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Inner Beans

    Self Study Inner Beanso Anonymous bean configuration inside another bean configuration.

    Link: Spring Inner Bean

    http://www.javabeat.net/tips/95-inner-beans-in-spring-ioc.htmlhttp://www.javabeat.net/tips/95-inner-beans-in-spring-ioc.html
  • 7/31/2019 Bean Wiring - Training Prez New

    27/67

    27 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Exercise | Investment Portal | Scope & Factory Method

    Implement the following in the portal classes:o Make the Orderbean with scope Prototype.

    o Create a LogFactorysingleton class and call its getInstance method to instantiate a bean.

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

    Solution: Refer com.sapient.scoping package

  • 7/31/2019 Bean Wiring - Training Prez New

    28/67

    28 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Autowiring

  • 7/31/2019 Bean Wiring - Training Prez New

    29/67

    29 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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:

  • 7/31/2019 Bean Wiring - Training Prez New

    30/67

    30 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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 orderManagerdefined then same creditCardAuthorizerinstance will be wired. (if this is therequirement, then its not a limitation)

  • 7/31/2019 Bean Wiring - Training Prez New

    31/67

    31 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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.

  • 7/31/2019 Bean Wiring - Training Prez New

    32/67

    32 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Autowiring | constructor

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

    Limitations:o Must wire all constructor argumentscant mix with constructor autowiring.

    o Exception thrown if Spring finds more than one bean whose type is assignable to a constructorparameter.

    o Exception thrown if dependencies of more than one constructor is satisfied by autowiring.

  • 7/31/2019 Bean Wiring - Training Prez New

    33/67

    33 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Autowiring | Best Practices

    Best Practices:

    AvoidXML basedautowiringo 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 autodetectautowiring

    o default-autowire attribute in the beans element in spring configuration

  • 7/31/2019 Bean Wiring - Training Prez New

    34/67

    34 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Exercise | Investment Portal | Autowiring

    Wire the creditCardAuthorizer property ofOrderManagerclasso Use XML based autowiring.

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

    Solution: Refer com.sapient.autowire package

  • 7/31/2019 Bean Wiring - Training Prez New

    35/67

    35 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Parent-Child Beans

  • 7/31/2019 Bean Wiring - Training Prez New

    36/67

    36 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Parent-Child Beans | constructor

    Bean definitions in configuration xmls can show parent-child relationship. This cuts down redundant XML in context definition file.

    element provides two attributes:o Parent Indicates the id of a bean which is the parent of the bean having the parentattribute.

    o AbstractIf set to true, declaration is abstract and cant be instantiated by Spring.

  • 7/31/2019 Bean Wiring - Training Prez New

    37/67

    37 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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.

  • 7/31/2019 Bean Wiring - Training Prez New

    38/67

    38 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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.

  • 7/31/2019 Bean Wiring - Training Prez New

    39/67

    39 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Exercise | Investment Portal | Inheritance

    Write the following classes to implement Inheritance in Investment Portalo Rename CreditCardAuthorizer interface to CardAuthorizer interface.

    o CardAuthorizerImpl: Implements CardAuthorizerInterfaceo CardAuthorizerImpl: Attribute: externalAuthorizerURL, userId, password.

    o DebitCardAuthorizerImpl extends CardAuthorizerImpl

    o CreditCardAuthorizerImpl extends CardAuthorizerImpl

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

    Solution: Refer com.sapient.inheritance package

  • 7/31/2019 Bean Wiring - Training Prez New

    40/67

    40 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Injecting non-spring beans

  • 7/31/2019 Bean Wiring - Training Prez New

    41/67

    41 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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=trueo This means Spring container should not instantiate the bean instantiated outside the

    container.

  • 7/31/2019 Bean Wiring - Training Prez New

    42/67

    42 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Injecting non-spring beans (Contd..)

    Annotate the bean with @Configurable(). 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 theSpring container.

  • 7/31/2019 Bean Wiring - Training Prez New

    43/67

    43 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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

  • 7/31/2019 Bean Wiring - Training Prez New

    44/67

    44 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Exercise | Investment Portal | Non-Spring Beans

    Implement the necessary changes to instantiate OrderManager class outside the scope ofcontainer.

    The property OrderManager.creditCardAuthorizershould be set through bean wiring.

    Solution: Refer com.sapient.nonspring package

  • 7/31/2019 Bean Wiring - Training Prez New

    45/67

    45 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    External Configuration Properties & Property Editors

  • 7/31/2019 Bean Wiring - Training Prez New

    46/67

    46 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Externalizing Configuration Properties

    Application Specific Configurations vs. Deployment Specific Configurationso Application Specific Spring Configuration. For ex. Inter-objects dependencies

    o Deployment Specific External properties file. For ex. Connection URL

    PropertyPlaceholderConfigurero Pulls values from properties file into bean definitions.

    Values in properties fileo =

    o For ex. oms.authorizeduser=xyz

  • 7/31/2019 Bean Wiring - Training Prez New

    47/67

    47 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Externalizing Configuration Properties

    Syntax to fetch the propertieso ${placeholder-variable}

  • 7/31/2019 Bean Wiring - Training Prez New

    48/67

    48 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Internationalization

    Display text in users native language.

    If resource bundle is omso oms.properties - Default

    o oms_en_US.properties English speaking people in US

    o oms_hi_IN.properties Hindi Speaking people in India

    ResourceBundleMessageSourceo Id has to be messageSource

    ApplicationContext.getMessageo Parameters Message key, argument and locale

  • 7/31/2019 Bean Wiring - Training Prez New

    49/67

    49 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Property Editors

    Wiring String value to non-String type or vice-versa. Simplifies bean wiring of some data types likejava.io.File, java.util.Date, java.lang.class etc.

    Java.beans.PropertyEditorSupporto 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 PropertyEditorso FileEditor java.io.Fileo URLEditor java.net.URL

    o LocaleEditor java.util.Locale

    o CustomDateEditor java.util.Date

    o ClassEditor java.lang.Class

    o StringArrayPropertyEditor Comma delimited String to String array.

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

  • 7/31/2019 Bean Wiring - Training Prez New

    50/67

    50 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Exercise | Investment Portal | External Config

    Add a new attribute threadCount in OrderManager and read its value from oms.properties filepresent in the same package.

    Make the above threadCount locale dependant and read its local specific value from theproperties file.

    Solution: Refer com.sapient.externalconfig package

  • 7/31/2019 Bean Wiring - Training Prez New

    51/67

    51 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    P namespace and util schema

  • 7/31/2019 Bean Wiring - Training Prez New

    52/67

    52 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    P-Namespace

    Shortcut for defining properties.

  • 7/31/2019 Bean Wiring - Training Prez New

    53/67

    53 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Util Schema

    Utility configuration issueso Referencing constants

    o Configuring collectionso Etc

    o Set a constant value(e.g. 'java.sql.Connection.TRANSACTION_SERIALIZABLE) to a property value.

    o Creating a bean having the value equal to the x property of y bean.

    o Instantiate java.util.Properties instance with the values loaded from Resource location.

    o Explicity control the exact type of list which will be instantiated.

    Refer: com.sapient.beanwiring.util package

  • 7/31/2019 Bean Wiring - Training Prez New

    54/67

    54 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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

  • 7/31/2019 Bean Wiring - Training Prez New

    55/67

    55 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Exercise | Util Schema

    Write LoginDao and LogoutDao with the following properties

    LoginDaoo isolationLevel Set the value java.sql.Connection.TRANSACTION_SERIALIZABLEo propertySet - java.util.Properties Populate the properties from jdbc.properties

    LogoutDaoo

    isolationLevel Set the value LoginDao. isolationLevelo logoutPages logoutPages: List - Populate set of three pages in the LinkedList

    Solution: Refer com.sapient.util

  • 7/31/2019 Bean Wiring - Training Prez New

    56/67

    56 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Annotation based dependency injection

  • 7/31/2019 Bean Wiring - Training Prez New

    57/67

    57 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    @Autowired

    XML Based Wiring Limitationso 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

    RegisteringAutowiredAnnotationBeanPostProcessor

  • 7/31/2019 Bean Wiring - Training Prez New

    58/67

    58 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    @Qualifier

    Specifying a candidate bean name when more than one bean with compatible type incontainer

    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.

  • 7/31/2019 Bean Wiring - Training Prez New

    59/67

    59 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Component Scanning

    Limitation:

    Every bean declared manually in configuration file.

    What if Spring automatically detects the components?

    Spring supports:o @Component Basic Annotation

    o @Repository Components in Persistence Layer

    o @Service Components in Service Layer

    o @Controller Components in Presentation Layer

    ( )

  • 7/31/2019 Bean Wiring - Training Prez New

    60/67

    60 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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()

    Scanning can be customized by applying include/exclude filters. Scanning Annotations not required if a class is defined in include-filter. Types

    o Annotation Annotation type

    o Assignable - Class/Interface for filtering

    o Regex Regular Expression

    o Aspectj Pointcut expression matching the classes

    | l |

  • 7/31/2019 Bean Wiring - Training Prez New

    61/67

    61 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Exercise | Investment Portal | Annotations

    Modify the Spring configuration file to Autowire the property of OrderManager class throughAnnotation.

    Scan all the bean definitions in the given package than manually defining them in the config file.

    Solution: Refer com.sapient.autowire.annotation

  • 7/31/2019 Bean Wiring - Training Prez New

    62/67

    62 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Additional Best Practices

    Additi l B t P ti

  • 7/31/2019 Bean Wiring - Training Prez New

    63/67

    63 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Additional Best Practices

    Prefer ApplicationContext over BeanFactoryo ApplicationContext supports i18n, Resource Loading and Eventso

    BeanFactory preferred when there is limitation on resources and size of application. For ex.Applets, Mobile Applications.

    Bean Naming Conventiono Use clear, descriptive naming convention for beanso Recommendation: CamelCase.o Use Java naming convention for classes with first alphabet in lowercase

    Inner Beanso Use when bean only available to a parent bean

    Use or null propertyo 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.

    B t P ti

  • 7/31/2019 Bean Wiring - Training Prez New

    64/67

    64 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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.

  • 7/31/2019 Bean Wiring - Training Prez New

    65/67

    65 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    Appendix - A

    E i | S l ti

  • 7/31/2019 Bean Wiring - Training Prez New

    66/67

    66 COPYRIGHT 2011 SAPIENT CORPORATION | CONFIDENTIAL

    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 attachedzip.

    Click Finish.

  • 7/31/2019 Bean Wiring - Training Prez New

    67/67

    Thank You!