• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
2. wiring beans
 

2. wiring beans

on

  • 844 views

 

Statistics

Views

Total Views
844
Views on SlideShare
844
Embed Views
0

Actions

Likes
1
Downloads
49
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    2. wiring beans 2. wiring beans Presentation Transcript

      • Wiring Beans
        Francesco Ierna
    •  
      • DI
      • DI : The act of creating these associations between application objects is the essence of DI and is commonly referred to as wiring In Spring, objects aren’t responsible for finding or creating the other objects that they need to do their jobs. Instead, they’re given references to the objects that they collaborate with by the container.
      • Class can be constructed in different ways
        • Using the default constructor
        • Using a constructor that takes an int argument which indicates the number of beanbags that the Juggler will attempt to keep in the air
        • factory-created beans through the <bean> element’s factory-method attribute.
      • Create Beans Simple Example
      • Create Beans Examples
      Constructor Default <bean id=&quot;duke&quot; class=&quot;com.springinaction.springidol.Juggler&quot; /> Juggler juggler = new Juggler(); Constructor with primitive type <bean id=&quot;duke&quot; class=&quot;com.springinaction.springidol.Juggler&quot;> <constructor-arg value=&quot;15&quot; /> </bean> Juggler juggler = new Juggler(15); Constructor with primitive type and an referecence to another bean. <bean id=&quot;sonnet29&quot; class=&quot;com.springinaction.springidol.Sonnet29&quot; /> <bean id=&quot;poeticDuke&quot; class=&quot;com.springinaction.springidol.PoeticJuggler&quot;> <constructor-arg value=&quot;15&quot; /> <constructor-arg ref=&quot;sonnet29&quot; /> </bean> Poem sonnet29 = new Sonnet29(); Performer duke = new PoeticJuggler(15, sonnet29); Constructor with factory - method <bean id=&quot;theStage&quot; class=&quot;com.springinaction.springidol.Stage&quot; factory-method=&quot;getInstance&quot; / > public static Stage getInstance() { return StageSingletonHolder.instance; }
      • Bean Scoping
      • Init – Destroy Beans
      • DEF : When a bean is instantiated, it may be necessary to perform some initialization to get it into a usable state. Likewise, when the bean is no longer needed and is removed from the container, some cleanup may be in order
        • Default : If many of the beans in a context definition file will have initialization or destroy methods with the same name, you don’t have to declare init-method or destroy-method on each individual bean
      • Injection Overview
      • Injecting into properties : Spring can take advantage of a property’s setter method to configure the property’s value through setter injection
      • Differents types of wiring:
        • With brackets <> :
          • Inecting simple values with <property> : is similar to <constructor-arg> in many ways, except that instead of injecting values through a constructor argument, <property> injects by calling a property’s setter method. Spring will use property setter methods to inject values into the properties specified by <property> elements.
            • The value attribute can also specify numeric ( int , float , java.lang.Double, Boolean ) values
          • Referencing other beans : has been injected with all of its properties and Kenny is ready to perform
          • Inner beans : An inner bean is defined by declaring a <bean> element directly as a child of the <property> element to which it’ll be injected
            • beans aren’t limited to setter injection . You may also wire inner beans into constructor arguments .
            • don’t have an id attribute set. not necessary because you’ll never refer to the inner bean by name
            • they can’t be reused . They're only useful for injection once and can’t be referred to by other beans
        • Without brackets : but importing the schema P xmlns:p=&quot;http://www.springframework.org/schema/p&quot;
          • you can now use p: -prefixed attributes of the <bean> element to wire properties
      • Wiring With Brackets Overview
      Simple Properties: <bean id=&quot;kenny&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> <property name=&quot;age&quot; value=&quot;37&quot; /> </bean> Referring other beans: <bean id=&quot;saxophone&quot; class=&quot;com.springinaction.springidol.Saxophone&quot; /> <bean id=&quot;kenny2&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> <property name=&quot;instrument&quot; ref=&quot;saxophone&quot; /> </bean> Inner Beans <bean id=&quot;kenny&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> <property name=&quot;instrument&quot;> <bean class=&quot;org.springinaction.springidol.Saxophone&quot; /> </property> </bean> <bean id=&quot;duke&quot; class=&quot;com.springinaction.springidol.PoeticJuggler&quot;> <constructor-arg value=&quot;15&quot; /> <constructor-arg> <bean class=&quot;com.springinaction.springidol.Sonnet29&quot; /> </constructor-arg> </bean>
      • Wiring With Brackets Overview
      Simple Properties: <bean id=&quot;kenny&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> <property name=&quot;age&quot; value=&quot;37&quot; /> </bean> Referring other beans: <bean id=&quot;saxophone&quot; class=&quot;com.springinaction.springidol.Saxophone&quot; /> <bean id=&quot;kenny2&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> <property name=&quot;instrument&quot; ref=&quot;saxophone&quot; /> </bean> Inner Beans <bean id=&quot;kenny&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> <property name=&quot;instrument&quot;> <bean class=&quot;org.springinaction.springidol.Saxophone&quot; /> </property> </bean> <bean id=&quot;duke&quot; class=&quot;com.springinaction.springidol.PoeticJuggler&quot;> <constructor-arg value=&quot;15&quot; /> <constructor-arg> <bean class=&quot;com.springinaction.springidol.Sonnet29&quot; /> </constructor-arg> </bean>
      • Injection Overview 2
      • List, Set: element contains one or more values. as the members of a <list>, including <value>, <bean>, and <null/> .
        • that are of any implementation of java.util.Collection or an array
        • polirmorfismo
      • Map : is a java.util.Map : The <map> element declares a value of type java.util.Map. Each <entry> element defines a member of the Map. In the previous example, the key attribute specifies the key of the entry whereas the value-ref attribute defines the value of the entry as a ref-erence to another bean within the Spring context.
      • Wiring With Brackets Overview
      Simple Properties: <bean id=&quot;kenny&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> <property name=&quot;age&quot; value=&quot;37&quot; /> </bean> Referring other beans: <bean id=&quot;saxophone&quot; class=&quot;com.springinaction.springidol.Saxophone&quot; /> <bean id=&quot;kenny2&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> <property name=&quot;instrument&quot; ref=&quot;saxophone&quot; /> </bean> Inner Beans <bean id=&quot;kenny&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> <property name=&quot;instrument&quot;> <bean class=&quot;org.springinaction.springidol.Saxophone&quot; /> </property> </bean> <bean id=&quot;duke&quot; class=&quot;com.springinaction.springidol.PoeticJuggler&quot;> <constructor-arg value=&quot;15&quot; /> <constructor-arg> <bean class=&quot;com.springinaction.springidol.Sonnet29&quot; /> </constructor-arg> </bean>
      • Injection Overview 2
      • Types of wiring :
        • List
        • Set
        • Map
        • Properties
      • List - Set
      • List – Set : any implementation of java.util.Collection or an array .
        • Contains one or more values. value-setting Spring elements as the members of a <list> , including <value> , <bean> , and <null/>.
        • A <list> may contain another <list> as a member for multidi-mensional lists.
        • Either <list> or <set> can be used to wire any implementation of java.util.Collection or an array
      • Map
      • Map : element declares a value of type java.util.Map . Each <entry> element defines a member of the Map . In the previous example, the key attribute specifies the key of the entry whereas the value-ref attribute defines the value of the entry as a ref-erence to another bean within the Spring context.
      • Properties
      • Properties : if you find yourself configuring a Map whose entries have both String keys and String values
        • The <props> element constructs a java.util.Properties value where each member is defined by a <prop> element. Each <prop> element has a key attribute that defines the key of each Properties member, while the value is defined by the contents of the <prop> element.
      • It’s important to keep the following straight:
        • <property> is the element used to inject a value or bean reference into a prop- erty of a bean class.
        • <props> is the element used to define a collection value of type java.util .Properties .
        • <prop> is the element used to define a member of a <props> collection
    • SpEL Overview
      • SpEL : a powerful yet succinct way of wiring values into a bean’s properties or constructor arguments using expres-sions that are evaluated at runtime. The ultimate goal of a SpEL expression is to arrive at some value after evaluation. In the course of calculating that value, other values are considered and operated upon. The simplest kinds of values that SpEL can evaluate may be literal values, references to a bean’s properties, or perhaps a constant on some class.
      • #{} markers  : We could wire this value into a bean’s property by using #{} markers in a <property> element’s value
      • REFERENCING BEANS, PROPERTIES, AND METHODS :
        • The first part refers to the kenny bean by its ID. The second part refers to the song attribute of the kenny bean.
        • null-safe accessor ? operator : Instead of a lonely dot (.) to access the toUpperCase() method, now you’re using ?. operator. This operator makes sure that the item to its left isn’t null before accessing the thing to its right
      • Performing operations : Arithmetic , Relational , Logical , Conditional , Regular expression
    • SpEL Overview
      • SpEL Examples
      Accessing properties <bean id=&quot;carl&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;#{kenny.song}&quot; /> </bean> Null-Safe operator <property name=&quot;song&quot; value=&quot;#{songSelector.selectSong()?.toUpperCase()}&quot;/> Types <property name=&quot;multiplier&quot; value=&quot;#{T(java.lang.Math).PI}&quot;/> Arithmetics <property name=&quot;adjustedAmount&quot; value=&quot;#{counter.total + 42}&quot;/> <property name=&quot;average&quot; value=&quot;#{counter.total / counter.count}&quot;/> Comparable <property name=&quot;equal&quot; value=&quot;#{counter.total == 100}&quot;/> <property name=&quot;hasCapacity&quot; value=&quot;#{counter.total le 100000}&quot;/> Logical <property name=&quot;outOfStock&quot; value=&quot;#{!product.available}&quot;/> <property name=&quot;outOfStock&quot; value=&quot;#{not product.available}&quot;/> Ternar <property name=&quot;song&quot; value=&quot;#{kenny.song ?: 'Greensleeves'}&quot;/> Regular Expression <property name=&quot;validEmail&quot; value= &quot;#{admin.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.com'}&quot;/>
    • Autowiring
      • Autowiring: Spring offers autowiring. Rather than explicitly wiring bean properties, why not let Spring sort out those cases when there’s no question about which bean reference should be wired
      • Four kind of autowiring :
        • byName —Attempts to match all properties of the autowired bean with beans that have the same name (or ID) as the properties. Properties for which there’s no matching bean will remain unwired
        • byType —Attempts to match all properties of the autowired bean with beans whose types are assignable to the properties. Properties for which there’s no matching bean will remain unwired.
        • constructor —Tries to match up a constructor of the autowired bean with beans whose types are assignable to the constructor arguments
        • autodetect —Attempts to apply constructor autowiring first. If that fails, byType will be tried
        • Default  : I said that default-autowire would be applied to all beans in a given Spring configuration file . I didn’t say that it would be applied to all beans in a Spring application context. You could have multiple configuration files that define a single application context, each with their own default autowiring setting.
          • You can still override the default on a bean-by-bean basis using the autowire attribute.
      • Autowiring byName
      byName autowiring establishes a convention where a property will automatically be wired with a bean of the same name. We had: <bean id=&quot;kenny2&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> <property name=&quot;instrument&quot; ref=&quot;saxophone&quot; /> </bean> And now by the Autowiring instrument will be autowired automatically into the kenny bean. We need set(idBean) within the kenny Bean: <bean id=&quot;instrument&quot; class=&quot;com.springinaction.springidol.Saxophone&quot; /> <bean id=&quot;kenny&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot; autowire=&quot;byName&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> </bean>
      • Autowiring byType
      • byType autowiring When attempting to autowire a property by type, Spring will look for beans whose type is assignable to the property’s type. But there’s a limitation to autowiring by type. What happens if Spring finds more than one bean whose type is assignable to the autowired property? In such a case, Spring isn’t going to guess which bean to autowire and will instead throw an excep-tion.We can have only one bean configured that matches the autowired property
      • To overcome ambiguities with autowiring by type, Spring offers two options: you can either identify a primary candidate for autowiring or you can eliminate beans from autowiring candidacy
      We had: <bean id=&quot;kenny2&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> …. <property name=&quot;instrument&quot; ref=&quot;saxophone&quot; /> </bean> And now by the Autowiring instrument will be autowired automatically into the kenny bean. We need set with the same type within the kenny Bean: <bean id=&quot;instrument&quot; class=&quot;com.springinaction.springidol.Saxophone&quot; /> <bean id=&quot;kenny&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot; autowire=&quot;byType&quot;> <property name=&quot;song&quot; value=&quot;Jingle Bells&quot; /> </bean> Primary Candidate: <bean id=&quot;saxophone&quot; class=&quot;com.springinaction.springidol.Saxophone&quot; primary=&quot;false&quot; /> Eliminate beans from autowiring: <bean id=&quot;saxophone&quot; class=&quot;com.springinaction.springidol.Saxophone&quot; autowire-candidate=&quot;false&quot; />
      • Autowiring byConstructor
      byConstructor autowiring is configured using constructor injection, you may choose to put away the <constructor-arg> elements and let Spring automatically choose constructor arguments from beans in the Spring context. Spring to look at Poetic- Juggler ’s constructors and try to find beans in the Spring configuration to satisfy the arguments of one of the constructors. It shares the same limitations as byType . Spring won’t attempt to guess which bean to autowire when it finds multiple beans that match a con-structor’s arguments. We had: <bean id=&quot;kenny2&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> …. <property name=&quot;instrument&quot; ref=&quot;saxophone&quot; /> </bean> And now by the Autowiring instrument will be autowired automatically into the kenny bean. We need a constructor with the same type of Pome the kenny Bean: <bean id=&quot;instrument&quot; class=&quot;com.springinaction.springidol.Saxophone&quot; /> <bean id=&quot;duke&quot; class=&quot;com.springinaction.springidol.PoeticJuggler&quot; autowire=&quot;constructor&quot; />
      • Autowiring byConstructor
      byConstructor autowiring is configured using constructor injection, you may choose to put away the <constructor-arg> elements and let Spring automatically choose constructor arguments from beans in the Spring context. Spring to look at Poetic- Juggler ’s constructors and try to find beans in the Spring configuration to satisfy the arguments of one of the constructors. It shares the same limitations as byType . Spring won’t attempt to guess which bean to autowire when it finds multiple beans that match a con-structor’s arguments. We had: <bean id=&quot;kenny2&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> …. <property name=&quot;instrument&quot; ref=&quot;saxophone&quot; /> </bean> And now by the Autowiring instrument will be autowired automatically into the kenny bean. We need a constructor with the same type of Pome the kenny Bean: <bean id=&quot;instrument&quot; class=&quot;com.springinaction.springidol.Saxophone&quot; /> <bean id=&quot;duke&quot; class=&quot;com.springinaction.springidol.PoeticJuggler&quot; autowire=&quot;constructor&quot; />
    • Autowiring Annotation
      • Autowiring Annotation: Autowiring with annotations isn’t much different than using the autowire attribute in XML. But it does allow for more fine-grained autowiring, where you can selectively annotate certain properties for autowiring . Autowiring is not deafult. To autowire a bean we must annotate with @Autowired on the property and :
        • <context:annotation-config> tells Spring that you intend to use annotation-based wiring in Spring. We need to declare <bean> in a XML File config to autowire the bean, otherwise we'll take nullpointer over the var.
        • <context:component-scan> element works by scanning a package and all of its subpackages, looking for classes that could be automatically registered as beans in the Spring container. By adding <context:include-filter> and/or <context:exclude-filter> subelements to <context:component-scan> , you can tweak component-scanning behavior to your heart’s content.
          •  @Component : A general-purpose stereotype annotation indicating that the class is a Spring component
          • @Controller : Indicates that the class defines a Spring MVC controller
          • @Repository : Indicates that the class defines a data repository
          • @Service : Indicates that the class defines a service  Any custom annotation that is itself annotated with @Component
      • Combining with @Autowired :
        • @Qualifier : maybe the problem’s not a lack of beans for Spring autowiring to choose from. Maybe it’s an abundance of (or at least two) beans, each of which is equally qualified to be wired into a property or parameter . Using @Qualifier is a means of switching @Autowired ’s by-type autowiring into explicit by-name wiring
      • Instead of Autowired;
        • @Values : You may want to also use annotations to wire simpler values. Spring 3.0 intro-duced @Value , a new wiring annotation that lets you wire primitive values such as int , boolean , and String using annotations
      • Autowired with @ with <context-config>
      Autowiring annotation we need :
      • <beans xmlns=&quot;http://www.springframework.org/schema/beans&quot; …....&quot;>
      • <context:annotation-config />
      • <!-- bean declarations go here --> </beans>
      <bean id=&quot;kenny2&quot; class=&quot;com.springinaction.springidol.Instrumentalist&quot;> …. <property name=&quot;instrument&quot; ref=&quot;saxophone&quot; /> </bean> Autowiring byType: @Autowired public void setInstrument(Instrument instrument) { this.instrument = instrument; } Autowiring byType not in a setter method: @Autowired public void heresYourInstrument(Instrument instrument) { this.instrument = instrument; } Autowiring byConstructor: @Autowired public Instrumentalist(Instrument instrument) { this.instrument = instrument; } Autowiring in a private field: @Autowired private Instrument instrument. @Qualifier annotation will try to wire in a bean whose ID matches guitar. @Autowired @Qualifier(&quot;guitar&quot;) private Instrument instrument
      • Autowired with @ with <component-scan>
      • Autowired values with @
      Setting the value eruption into theString variable song @Value(&quot;Eruption&quot;) private String song; SpEL @Value(&quot;#{systemProperties.myFavoriteSong}&quot;) private String song;
      • Autowired values with Autodiscovery
      • Autowired values with Autodiscovery
      Scan on the package: <context:component-scan base-package=&quot;com.springinaction.springidol&quot;> </context:component-scan> the bean’s ID will be generated by camel-casing the claass name package com.springinaction.springidol; import org.springframework.stereotype.Component; @Component public class Guitar implements Instrument { public void play() { System.out.println(&quot;Strum strum strum&quot;); } } Filtering autoscan including assignable with type in expressione <context:component-scan base-package=&quot;com.springinaction.springidol&quot;> <context:include-filter type=&quot;assignable&quot; expression=&quot;com.springinaction.springidol.Instrument&quot;/> </context:component-scan> To register all Instrument implementations except for annotated with a custom @SkipIt <context:component-scan base-package=&quot;com.springinaction.springidol&quot;> <context:include-filter type=&quot;assignable&quot; expression=&quot;com.springinaction.springidol.Instrument&quot;/> <context:exclude-filter type=&quot;annotation&quot; expression=&quot;com.springinaction.springidol.SkipIt&quot;/> </context:component-scan>
      • Autowired values with Autodiscovery
      Scan on the package: <context:component-scan base-package=&quot;com.springinaction.springidol&quot;> </context:component-scan> the bean’s ID will be generated by camel-casing the claass name package com.springinaction.springidol; import org.springframework.stereotype.Component; @Component public class Guitar implements Instrument { public void play() { System.out.println(&quot;Strum strum strum&quot;); } } Filtering autoscan including assignable with type in expressione <context:component-scan base-package=&quot;com.springinaction.springidol&quot;> <context:include-filter type=&quot;assignable&quot; expression=&quot;com.springinaction.springidol.Instrument&quot;/> </context:component-scan> To register all Instrument implementations except for annotated with a custom @SkipIt <context:component-scan base-package=&quot;com.springinaction.springidol&quot;> <context:include-filter type=&quot;assignable&quot; expression=&quot;com.springinaction.springidol.Instrument&quot;/> <context:exclude-filter type=&quot;annotation&quot; expression=&quot;com.springinaction.springidol.SkipIt&quot;/> </context:component-scan>