Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Spring (part 2) Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack.

Similar presentations


Presentation on theme: "Introduction to Spring (part 2) Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack."— Presentation transcript:

1 Introduction to Spring (part 2) Matt Wheeler

2 Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic Java and XML skills – Introduction to Spring (part 1) – Installed LdsTech IDE (or other equivalent)

3 Review Last time we went over – Bean definitions – Dependency Injection (DI) and Inversion of Control (IoC) – Application context – Bean scopes

4 Review ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); SomeBean someBean = context.getBean(SomeBean.class); someBean.callMethod(); Bean definition (beans.xml) Application Context

5 Overview Bean lifecycle XML Schema-based configuration (namespace handlers) Lifecycle hooks Bean Initialization (JSR 250, @PostConstruct, …) Bean post processors Component scanning Spring Component Annotations DI Annotations (JSR 330, @Inject, @Named)

6 Spring Bean Lifecycle 1. Bean definitions created/registered (from xml or annotations, or, …) 2. Beans instantiated using the definitions 3. Dependencies set (values and bean references) on the newly instantiated beans 4. Bean initialization 5. Beans delivered to requester for use 6. Destruction callback method called at container shutdown

7 XML Schema-based configuration Also called namespace handlers Shorten bean definition configuration Provide easily reusable definitions Self documenting More readable NOTE: Takes place in the first phase of the bean lifecycle (i.e. while xml files are being parsed)

8 XML Schema-based configuration Example namespace handler Basically equivalent configuration

9 Wait that’s not all And this

10 Another Example Utilizing a namespace handler <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> abc def ghi jkl abc def ghi jkl

11 Demo DEMO

12 Spring XML Schema-based configurations SchemaDescription / Documentation utilCreate non-anonymous collection types that can be referenced by id http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/xsd-config.html#xsd-config-body-schemas-util jeeElements such as jndi support / ejb shortcuts http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/xsd-config.html#xsd-config-body-schemas-jee langExpose beans written in another language like JRuby or Groovy http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/xsd-config.html#xsd-config-body-schemas-lang jmsDeal with configuring JMS-related beans http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/xsd-config.html# xsd-config-body-schemas-jms txTransaction support http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/xsd-config.html# xsd-config-body-schemas-tx

13 XML Schema-based configuration (cont.) SchemaDescription / Documentation aopHelpers for Spring’s aspect oriented programming mechanisms http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/xsd-config.html# xsd-config-body-schemas-aop contextConfiguration related to the application context plumbing http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/xsd-config.html# xsd-config-body-schemas-context toolsConfiguration for adding tooling specific meta-data http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/xsd-config.html# xsd-config-body-schemas-tool securityProvides elements for web security configuration http://static.springsource.org/spring-security/site/docs/3.0.x/reference/ns- config.html mvcProvides interceptors, view-controller, ….. http://static.springsource.org/spring/docs/3.0.x/spring-framework- reference/html/mvc.html#mvc-config

14 XML Schema-based configuration arch. Parts of XML Schema-based configuration – Xml schema that describes allowable elements – Namespace handler (Java code) – BeanDefinitionParser (Java code) Parses the defined xml and adds any necessary beans into the configuration Bottom line – Namespace handlers are backed by code The code supplements bean configuration and is often a lot more than meets the eye

15 Bean Definition Parsers Let’s look at an example public class SomeBeanDefinitionParser implements BeanDefinitionParser { public AbstractBeanDefinition parse(Element element, ParserContext parserContext) { CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); parserContext.pushContainingComponent(compositeDef); BeanDefinitionBuilder someBeanDefinition = BeanDefinitionBuilder.genericBeanDefinition(SomeBean.class); if (Boolean.parseBoolean(element.getAttribute("some-attribute"))) { SomeBeanDefinition.addPropertyValue("someProperty", "abc"); } …

16 Lab 1: XML Schema-based configuration https://tech.lds.org/wiki/Introduction_to_Spring_C ontinued#Lab_1_Xml_Schema- based_configuration

17 Bean Initialization (JSR 250)

18 Spring Bean Lifecycle 1. Bean definitions created/registered (from xml or annotations, or, …) 2. Beans instantiated using the definitions 3. Dependencies set (values and bean references) on the newly instantiated beans 4. Bean initialization 5. Beans delivered to requester for use 6. Destruction callback method called at container shutdown

19 Hooking into the Lifecycle Assume the following class Define init-method to be called The init method is called after the bean has been initialized and all properties set public class SomeBean { public void init() { //some initialization code }

20 Jar Dependency JSR 250 Annotation Dependency (only required in Java 1.5) javax.annotation jsr250-api 1.0

21 JSR 250 Common Annotations The goal of JSR 250 was to come up with a standard set of annotations to accomplish common use cases in Java The annotations are outlined here: http://en.wikipedia.org/wiki/JSR_250 We will only be focusing on a tiny subset of these annotations in order to replace our init-method functionality

22 Annotate the Class JSR 250 annotations provides @PostConstruct annotation for bean initialization There is likewise an @PreDestroy counterpart – Called just before the bean is destroyed – Allows for cleanup of resources public class SomeBean { @PostConstruct public void init() { // do some initialization work }

23 Configure Annotation Handling Specify annotation handlers (bean post processors) <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:context=http://www.springframework.org/schema/context xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

24 Lab 2: JSR 250 Annotations https://tech.lds.org/wiki/Introduction_to_Spring_C ontinued#Lab_2_JSR_250_Annotations

25 Spring Component Annotations We have seen how to use annotations to call an init method during initialization Wouldn’t it be nice if didn’t need to define even the beans themselves in xml at all? – We will need something to scan the classes for annotations and register bean definitions

26 Welcome component-scan component-scan element in context schema – Scans classpath searching for matching beans Registers bean definitions for matching classes – Can specify an include filter and/or exclude filter You can also assign a filter type for a targeted search – http://static.springsource.org/spring/docs/3.0.x/spring- framework-reference/html/beans.html#beans-scanning-filters – annotation – assignable – regex – custom

27 Bean Lifecycle and Component Scan 1. Create bean definitions (from xml or annotations, or, …) 2. Instantiate beans using the definitions 3. Set bean dependencies (values and bean references) on the newly instantiated beans 4. Initialization 5. Deliver bean to requester for use 6. On container shutdown call destruction callback method

28 For Example This configuration will (for the given packages): – Register bean definitions for all classes with “abc” in their names – Not register beans for any classes that extend / implement Animal <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

29 Naming What id will be given for beans that are registered By default it is the class name with the first letter lower cased – For example, the following will result in a bean definition with id=“rabbit” @Component public class Rabbit { }

30 Naming What id will be given for beans that are registered? By default it is the class name with the first letter lower cased – For example, a class named Rabbit would result in a bean definition with id=“rabbit” – Package is dropped from the name

31 Annotation Scanning What do we do if: – The default naming is not acceptable – Difficult to come up with a pattern that matches only the beans that we want registered with Spring – What if we don’t want scope of singleton We can employ annotations and only register definitions for classes that are appropriately annotated

32 Spring Component Annotations Spring provides stereotype annotations to identify a bean’s role in the app. architecture – @Service – denotes application services – @Controller – denotes view layer components – @Component – the most general stereotype annotation – denotes any class to be managed by Spring – @Repositoy – most often used to demarcate DAOs – You can also create your own custom stereotype annotations

33 For Example In a given application context you may want to have the scanner selectively register definitions – Register beans annotated with your custom annotation – Once include is specified defaults are disabled <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

34 Naming So how does annotation scanning help naming? – The following will still register a bean with id=“rabbit” – But, this will register a bean with id=“crazyRabbit” – I.e. the annotations allow you to provide a specific name for the given bean to the bean definition parser @Component public class Rabbit { } @Component("crazyRabbit") public class Rabbit { }

35 The Main Point All this to tell you that now you can create a bean automatically without defining it in xml That is to say, the following are basically equivalent in function @Component("something") public class SomeBean { }

36 Scope But what about scope – What is the equivalent annotation for specifying a scope of prototype – @Scope("prototype")

37 @Scope Be sure to use org.springframework.context.annotation.Scope – Not javax.inject.Scope Possible values: – @Scope or @Scope("singleton") – @Scope("prototype") – @Scope("request") – @Scope("session")

38 Putting it all together Xml definition Equivalent annotation definition @Component @Scope("prototype") public class Turkey { }

39 Lab 3: Spring Component Annotations https://tech.lds.org/wiki/Introduction_to_Spring_C ontinued#Lab_3_Spring_Component_Annotation s

40 JSR 330 Annotations (DI) Now that we can create bean definitions how do we specify injection

41 Dependency JSR 330 annotations require you to include the following dependency: – Don’t be alarmed by the unorthodox version value It is correct as of this writing javax.inject 1

42 Dependency Injection Annotations To inject beans we have the following new annotations – @Inject – inject bean references by type – @Named – modify injection by providing a name

43 @Inject @Inject can be used almost anywhere //on a member variable @Inject private Rabbit rabbit; //on a constructor @Inject public Farm(Rabbit prizeRabbit) {…} //on a setter method @Inject public void setPrizeRabbit(Rabbit rabbit) { this.rabbit = rabbit; } //if you can’t inject all of them by type you could use @Named to narrow to a single match @Inject public void anyMethod(Chicken chicken, @Named("prototypeRabbit") Rabbit rabbit, Duck duck) { … } //on collections (will inject all beans in the application context of the specified type) @Inject private Rabbit[] rabbits; @Inject private List rabbits; //will contain all beans with the given type and the bean name as the key @Inject private Map rabbits;

44 @Inject (cont) By default injection injects by type – Finds any registered instances of the type for the annotated type What if you have two targets of the same type? – You can specify by name – Downside is that this is no longer type safe Only referenced by a String Could employ a Qualifier to remain type safe http://static.springsource.org/spring/docs/3.0.x/spring- framework-reference/html/beans.html#beans-autowired- annotation-qualifiers @Inject @Named("prototypeRabbit") private Rabbit prizeRabbit;

45 Putting it all together Xml definition Somewhat equivalent annotation definition @Component public class Turkey { … } @Component(" billysFarm ") public class Farm { private Turkey turkey; @Inject public Farm(Turkey turkey) { this.turkey = turkey; }

46 DEMO ??? Assume the following configuration Now say I wanted to get rid of the chicken declaration Remove the chicken xml declaration Remove the farm xml declaration Assume the following configuration Of course our farm would look something like this: public class Farm { private Chicken chicken; public void setChicken(Chicken chicken) { this.chicken = chicken; } … }

47 Lab 4: JSR 330 (DI) Annotations https://tech.lds.org/wiki/Introduction_to_Spring_C ontinued#Lab_4_JSR_330_Annotations

48 Credit where credit is due http://springsource.org Spring Recipies 2 nd Edition (Gary Mak, Josh Long and Daniel Rubio)


Download ppt "Introduction to Spring (part 2) Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack."

Similar presentations


Ads by Google