matt wheeler n.
Skip this Video
Loading SlideShow in 5 Seconds..
Matt Wheeler PowerPoint Presentation
Download Presentation
Matt Wheeler

Matt Wheeler

81 Vues Download Presentation
Télécharger la présentation

Matt Wheeler

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Introduction to Spring Continued 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 • 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 • Bean definition (beans.xml) <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns:xsi="" xsi:schemaLocation=""> <bean class="" /> </beans> • Application Context ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); SomeBeansomeBean = context.getBean(SomeBean.class); someBean.callMethod();

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

  6. Spring Bean Lifecycle 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

  7. Section 1: XML Schema-based configuration • Also called namespace handlers • Shorten bean definition configuration • Provide easily reusable definitions • Self documenting • More readable

  8. XML Schema-based configuration • Example namespace handler • Basically equivalent configuration <mvc:annotation-driven validator="validator" /> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="order" value="0"/> <property name="useDefaultSuffixPattern" value="false"></property> </bean> <bean class="org.springframework.web.servlet.handler.MappedInterceptor"> <constructor-arg value="null"></constructor-arg> <constructor-arg> <bean class="org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor"> <constructor-arg> <bean class=""></bean> </constructor-arg> </bean> </constructor-arg> </bean>

  9. Wait that’s not all And this <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean id="webBindingInitializer" class=""> <property name="validator" ref="validator" /> <property name="conversionService"> <bean class="" /> </property> </bean> </property> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="writeAcceptCharset" value="false" /> </bean> <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"></bean> <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"></bean> <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"></bean> <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"></bean> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean>

  10. Spring XML Schema-based configurations

  11. XML Schema-based configuration (cont.)

  12. Another Example • Utilizing a namespace handler <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns:xsi="" xmlns:util="" xsi:schemaLocation=""> <!-- creates a java.util.Set instance with the supplied values --> <util:setid="alphaGroups"> <value>abc</value> <value>def</value> <value>ghi</value> <value>jkl</value> </util:set> </beans> <bean id="alphaGroups" class="org.springframework.beans.factory.config.SetFactoryBean"> <property name="sourceSet"> <set> <value>abc</value> <value>def</value> <value>ghi</value> <value>jkl</value> </set> </property> </bean>

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

  14. Bean Definition Parsers • Bottom line • Namespace handlers are backed by code • The code supplements bean configuration and is often a lot more than meets the eye • Let’s look under the hood of one

  15. Bean Definition Parser Demo DEMO

  16. Lab 1: XML Schema-based configuration

  17. Section 2: JSR 250 (Common) Annotations • JSR 250 provides many annotations for common use cases in Java

  18. Spring Bean Lifecycle Review 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

  19. Hooking into the Lifecycle • Define init-method in bean definition • The associated bean • The init method is called after the bean had been initialized an all properties set <bean id="whatever" init-method="init" class="" /> public class SomeBean { public void init() { //some initialization code } }

  20. 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 } }

  21. Configure Annotation Handling • Specify annotation handlers (bean post processors) <beans xmlns="" xmlns:xsi="" xsi:schemaLocation=""> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> </beans> <!– or --> <beans xmlns="" xmlns:xsi= xmlns:context= xsi:schemaLocation=""> <context:annotation-config /> </beans>

  22. Lab 2: JSR 250 Annotations

  23. Spring 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

  24. 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 • • annotation • assignable • aspectj • regex • cutsom

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

  26. 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="" xmlns:xsi="" xmlns:context="" xsi:schemaLocation=""> <context:component-scan base-package=","> <context:include-filter expression="org\.lds\.training\..*abc.*" type="regex"/> <context:exclude-filter expression=“" type="assignable"/> </context:component-scan> </beans>

  27. 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”

  28. 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 • We can employ annotations and only register definitions for classes that are appropriately annotated

  29. Spring Annotations • Spring provides stereotype annotations to help identify a bean’s role in the application • @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

  30. For Example • In a given application context you may want to have the scanner selectively register definitions • Register beans annotated with your custom annotation • But not register definitions for beans annotated with @Service <beans xmlns="" xmlns:xsi="" xmlns:context="" xsi:schemaLocation=""> <context:component-scan base-package=""> <context:include-filter expression="" type="annotation"/> <context:exclude-filter expression="org.springframework.stereotype.Service" type="annotation"/> </context:component-scan> </beans>

  31. 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 { }

  32. 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 <bean id="something" class="" /> @Component("something") public class SomeBean { }

  33. Scope • But what about scope • What is the equivalent annotation for specifying a scope of prototype • @Scope("prototype") <bean id="something" class="" scope="prototype"/>

  34. @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")

  35. Putting it all together • Xml definition • Equivalent annotation definition <bean id="turkey" class="" scope="prototype"> @Component @Scope("prototype") public class Turkey { }

  36. Lab 3: Spring Annotations

  37. Section 4: JSR 330 Annotations (DI) • Now that we can create bean definitions from annotations we probably would like to be able to inject one bean into another

  38. 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 <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency>

  39. 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 • @Inject is similar to specifying the following in a bean definition file <constructor-arg ref="rabbit" /> <!– or --> <property name="prizeRabbit" ref="rabbit" />

  40. @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<Rabbit> rabbits; //will contain all beans with the given type and the bean name as the key @Inject private Map<String, Rabbit> rabbits;

  41. @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 • @Inject @Named("prototypeRabbit") private Rabbit prizeRabbit;

  42. Putting it all together • Xml definition • Equivalent annotation definition <bean id="billysFarm" class=""> <constructor-arg name="turkey" ref="turkey" /> </bean> @Component public class Turkey { … } @Component(" billysFarm ") public class Farm { private Turkey turkey; @Inject public Farm(Turkey turkey) { this.turkey = turkey; } }

  43. Lab 4: JSR 330 (DI) Annotations

  44. Credit where credit is due • • Spring Recipies 2nd Edition (Gary Mak, Josh Long and Daniel Rubio)