Intermediate Spring Matt Wheeler
Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic Java and XML skills – Installed LdsTech IDE (or other equivalent – good luck there ;)
Review Bean lifecycle XML Schema-based Configuration (namespace handlers) Lifecycle hooks Bean Initialization (JSR …) Bean post processors Component scanning Spring Component Annotations DI Annotations
Overview Advanced Injection Spring EL Additional Injection Annotations Providers Application Context web integration Testing framework
Spring EL (SpEL) Allows access to Spring beans and properties Supports querying and manipulating object graph at runtime Similar syntax to Unified EL (but more extensive) – Method invocation, string templating Namespace handlers use it to inject references into attributes For more specifics, please see the Spring docs: – g-framework-reference/html/expressions.html
Spring EL Examples We recommend only using this when necessary – For example When extracting a property from a map Or injecting a reference into a namespace handler <data-source driver-class="org.h2.Driver" url="jdbc:h2:mem:stack-starter;MODE=Oracle" user="#{databaseUsername}" password="#{databasePassword}" override="true" db-env="EMBEDDED"/>
Additional Injection Annotations Many additional injection annotations Please refer to the Spring documentation here: – ng-framework-reference/html/beans.html#beans- annotation-config AnnotationExampleDescription private String something Spring EL can be used in correlation to inject a property private SomeBean someBean; Injects by name instead of type. Slight differences Used for injecting Collections. If name not explicitly specified it uses the name of the property being private SomeBean someBean; Spring proprietary annotation almost equivalent to JSR but with a required attribute.
Providers Providers allow us to defer instantiation or accessing a resource until it is accessed Providers facilitate (from the JavaDoc): – Retrieving multiple instances – Lazy or optimal retrieval of an instance – Breaking circular dependencies – Abstracting scope so you can look up an instance in a smaller scope from an instance in a containing scope
Previous Training Lab We used annotation to select the prototypeRabbit to inject into the farm as the prize rabbit The result was something like the following Does anyone see any problem with public class private Rabbit prizeRabbit; … }
Provider Demo DEMO
Lab 1: Providers _1_Advanced_Injection
Web Context Listener Loading application context in a web environment
Traditionally Previously we have loaded application contexts with something like: In a web environment however – You will want the context to automatically be loaded on startup – And be shared across the entire application ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); SomeBean someBean = context.getBean(SomeBean.class);
Servlet Listeners The Java Servlet spec provides a listener (startup hook) – Listeners triggered to run on startup Spring utilized this functionality and created a listener that will load the application context on start up
Context Loader Listener Here is the web.xml configuration: And utilizes the following context parameter org.springframework.web.context.ContextLoaderListener contextConfigLocation classpath:META- INF/spring/applicationContext.xml,classpath:*beans.xml classpath:anotherContext.xml
Application Contexts and Servlets Servlets not instantiated by Spring – Instantiated by the servlet container – Spring unable to inject dependencies However Spring provides a way to access the application context
Application Context and Servlet For the given servlet configuration (web.xml) Application Context accessed as follows: servlet org.lds.training.TrainingServlet servlet /servlet public class TrainingServlet extends HttpServlet protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Context loader listener stores context in the servlet context - which is why it is required ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); SomeBean someBean = (SomeBean) applicationContext.getBean(SomeBean.class); someBean.printSomething(); }
A Better Way Spring provides a servlet that delegates to a bean that is Spring managed – Called an HttpRequestHandler – Allows annotations and injection – Create a Spring bean that matches the name of the servlet name This provides the mapping between the two
Utilizing a Spring Request Handler The configuration: trainingHandler org.springframework.web.context.support.HttpRequestHandlerServlet trainingHandler public class TrainingRequestHandler implements HttpRequestHandler private SomeBean someBean; public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { someBean.printSomething(); }
Spring MVC and Application Contexts Spring MVC provides and even better way to integrate with the web container – Look forward to further discussion of this in a future training
Lab 2: Web Context Listener _2_Web_Context_Listener
Spring Testing Spring promotes testing in two prominent ways – Making the code more testable – Proving a testing framework
Testable Code Dependency injection decouples code from the container – POJOs are normally easier to test Dependencies are clearly defined
Testing Help Additionally we have an application context that can manage dependencies But reloading the context for each test would not be performant Spring provides support to load the context once per JVM (unless you explicitly tell it to reload)
Testing Framework Many good testing frameworks available – Junit – TestNG Spring provides test context classes that can be extended for the given test providers You can specify application contexts to be loaded
Spring Test – Allows you to specify application contexts to load – Important: Loaded in the order specified Searches last loaded first for a match and continues up chain until a matching bean is found Allows us to utilize everything in the project context – But override anything in the test contexts public class FarmIT extends AbstractTestNGSpringContextTests { //… }
DEMO
For example Regular application context Test application context
Stack Utils namespace handler (stack- utils:null) Alternatively, sometimes you would like the value to be null in a test – This can be accomplished with a Stack provided Xml- schema based configuration – For more information: utils/3.0.1/index.html utils/3.0.1/xsddoc/
Another example Regular application context Test application context <stack-db:data-source driver-class="org.h2.Driver" url="jdbc:h2:mem:stack-starter;MODE=Oracle" user="" password="" override="true" db-env="EMBEDDED"/>
Testing with a Database Suppose you wanted to use a database to test – Normally You would add data, run the test, and then clean it up – Spring provides transactional support so that the data from the test automatically rolls back after the test – Must extend AbstractTransactionalTestNGSpringContextTests Must specify a transaction manager in your bean definition
Lab 3: Spring Testing Integration _3_Spring_Testing_Integration
Credit where credit is due Spring Recipies 2 nd Edition (Gary Mak, Josh Long and Daniel Rubio)