2. wiring beans

Embed Size (px)

Citation preview

PRESENTATION NAME

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 arent responsible for finding or creating the other objects that they need to do their jobs. Instead, theyre 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 Jugglerwill attempt to keep in the air

factory-created beans through the elements factory-method attribute.

Create Beans Simple Example

Create Beans Examples

Constructor Default

Juggler juggler = new Juggler();

Constructor with primitive type Juggler juggler = new Juggler(15);

Constructor with primitive type and an referecence to another bean. Poem sonnet29 = new Sonnet29(); Performer duke = new PoeticJuggler(15, sonnet29);

Constructor with factory - method 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 dont have to declare init-method or destroy-method on each individual bean

Injection Overview

Injecting into properties: Spring can take advantage of a propertys setter method to configure the propertys value through setter injection

Differents types of wiring:With brackets :Inecting simple valueswith : is similar to in many ways, except that instead of injecting values through a constructor argument, injects by calling a propertys setter method. Spring will use property setter methods to inject values into the properties specified by 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 element directly as a child of the element to which itll be injected beans arent limited to setter injection. You may also wire inner beans into constructor arguments.

dont have an id attribute set. not necessary because youll never refer to the inner bean by name

they cant be reused. They're only useful for injection once and cant be referred to by other beans

Without brackets : but importing the schema Pxmlns:p="http://www.springframework.org/schema/p" you can now use p:-prefixed attributes of the element to wire properties

Wiring With Brackets Overview

Simple Properties:

Referring other beans:

Inner Beans

Wiring With Brackets Overview

Simple Properties:

Referring other beans:

Inner Beans

Injection Overview 2

List, Set: element contains one or more values. as the members of a , including , , and .that are of any implementation of java.util.Collection or an array

polirmorfismo

Map: is a java.util.Map: The element declares a value of type java.util.Map. Each 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:

Referring other beans:

Inner Beans

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 , including , , and .

A may contain another as a member for multidi-mensional lists.

Either or 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 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 valuesThe element constructs a java.util.Properties value where each member is defined by a element. Each element has a key attribute that defines the key of each Properties member, while the value is defined by the contents of the element.

Its important to keep the following straight:

is the element used to inject a value or bean reference into a prop-erty of a bean class.

is the element used to define a collection value of type java.util .Properties.

is the element used to define a member of a collection

SpEL Overview

SpEL: a powerful yet succinct way of wiring values into a beans 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 beans properties, or perhaps a constant on some class.

#{} markers: We could wire this value into a beans property by using #{} markers in a elements 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 youre using ?. operator. This operator makes sure that the item to its left isnt null before accessing the thing to its right

Performing operations: Arithmetic , Relational , Logical , Conditional , Regular expression

SpEL Overview

SpEL Examples

Accessing properties

Null-Safe operator

Types

Arithmetics

Comparable

Logical

Ternar

Regular Expression

Autowiring

Autowiring: Spring offers autowiring. Rather than explicitly wiring bean properties, why not let Spring sort out those cases when theres no question about which bean reference should be wired

Four kind of autowiring:byNameAttempts to match all properties of the autowired bean with beans that have the same name (or ID) as the properties. Properties for which theres no matching bean will remain unwired

byTypeAttempts to match all properties of the autowired bean with beans whose types are assignable to the properties. Properties for which theres no matching bean will remain unwired.

constructorTries to match up a constructor of the autowired bean with beans whose types are assignable to the constructor arguments

autodetectAttempts 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 didnt 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:

And now by the Autowiring instrument will be autowired automatically into the kenny bean. We need set(idBean) within the kenny Bean:

Autowiring byType

byType autowiring When attempting to autowire a property by type, Spring will look for beans whose type is assignable to the propertys type. But theres 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 isnt 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: .

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:

Primary Candidate: Eliminate beans from autowiring:

Autowiring byConstructor

byConstructor autowiring is configured using constructor injection, you may choose to put away the elements and let Spring automatically choose constructor arguments from beans in the Spring context. Spring to look at Poetic- Jugglers 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 wont attempt to guess which bean to autowire when it finds multiple beans that match a con-structors arguments.

We had: .

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:

Autowiring byConstructor

byConstructor autowiring is configured using constructor injection, you may choose to put away the elements and let Spring automatically choose constructor arguments from beans in the Spring context. Spring to look at Poetic- Jugglers 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 wont attempt to guess which bean to autowire when it finds multiple beans that match a con-structors arguments.

We had: .

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:

Autowiring Annotation

Autowiring Annotation: Autowiring with annotations isnt 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: tells Spring that you intend to use annotation-based wiring in Spring. We need to declare in a XML File config to autowire the bean, otherwise we'll take nullpointer over the var.

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 and/or subelements to , you can tweak component-scanning behavior to your hearts 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 problems not a lack of beans for Spring autowiring to choose from. Maybe its 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 @Autowireds 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

Autowiring annotation we need :