This document provides an overview of the Spring framework and inversion of control (IOC) design pattern. It discusses:
1) IOC allows externalizing application logic so it can be injected rather than written into client code. This separates implementation from client.
2) A car racing game example demonstrates how hard coding object creation leads to tight coupling. IOC solves this by describing object creation instead of performing it.
3) The Spring framework uses IOC through dependency injection configured via XML. This allows flexible object creation and injection into classes like Race without code changes.
Arjuna - The Case of Web UI Automation with SeleniumRahul Verma
The presentation starts with raw Selenium code for a basic scenario, discusses the challenges, and how to do better with Arjuna. Useful Arjuna-neutral framework building tips are shared across the slides.
How should a professional software developer behave in code? What guidelines should one follow? How should we name our constructs? What about OOP principles? What's their real use?
This classic training module in my training curricula is the cornerstone of my professionalism. These are my conduit guidelines at work. I've held this training > 10 times, including at Voxxed Days Bucharest 2016 and at a Bucharest Java User Group meetup.
Writing simple web services in java using eclipse editorSantosh Kumar Kar
This is a simple steps showing how you can write a simple web service, host into a server, write a client class to access the service on web server. Just for a beginners...
Arjuna - The Case of Web UI Automation with SeleniumRahul Verma
The presentation starts with raw Selenium code for a basic scenario, discusses the challenges, and how to do better with Arjuna. Useful Arjuna-neutral framework building tips are shared across the slides.
How should a professional software developer behave in code? What guidelines should one follow? How should we name our constructs? What about OOP principles? What's their real use?
This classic training module in my training curricula is the cornerstone of my professionalism. These are my conduit guidelines at work. I've held this training > 10 times, including at Voxxed Days Bucharest 2016 and at a Bucharest Java User Group meetup.
Writing simple web services in java using eclipse editorSantosh Kumar Kar
This is a simple steps showing how you can write a simple web service, host into a server, write a client class to access the service on web server. Just for a beginners...
Spring tutorial for beginners - Learn Java Spring Framework version 3.1.0 starting from environment setup, inversion of control (IoC), dependency injection, bean scopes, bean life cycle, inner beans, autowiring, different modules, aspect oriented programming (AOP), database access (JDBC), Transaction Management, Web MVC framework, Web Flow, Exception handling, EJB integration and Sending email etc.
Flashnoden Jani Karhusen esitys Verkkokauppa-Akatemian aamiaistilaisuudessa. Esityksessä avattiin Verkkokauppa-Akatemian konseptia ja kerrottiin samalla Flashnoden palvelusta verkkokauppiaille.
Paytrail – Näin saat verkkomaksupainikkeet ja kaikki muut maksutavat verkkoka...Paytrail
Esittely Paytrailin perinteisestä maksupalvelusta. Miten se toimii ja mitä maksutapoja se sisältää? Miten saat pankkipainikkeet ja kaikki maksutavat verkkokauppaasi?
Webinar: Spring Framework - Introduction to Spring WebMVC & Spring with BigData Edureka!
The free webinar on Spring Framework titled "Spring Framework - Introduction to Spring WebMVC & Spring with BigData" was conducted by Edureka on 18th November 2014
1. Introduction to Web Services
2. Web Service Architecture
3. What are Web Services?
4. Why are Web Services?
5. The base of WS
6. What is SOAP?
7. What is WSDL?
8. How to test a web service?
9. Examples
This document provides step by step instructions on how to achieve dependency injection using dagger 2. The code is written in java. The code content is courtesy of Coding In Flow - You can check out this channel for in-depth explanation. https://www.youtube.com/watch?v=ZZ_qek0hGkM&list=PLrnPJCHvNZuA2ioi4soDZKz8euUQnJW65
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxcurwenmichaela
Broncos/build.xml
Builds, tests, and runs the project Broncos.
Broncos/manifest.mf
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
Broncos/nbproject/build-impl.xml
Must set src.dir
Must set test.src.dir
Must set build.dir
Must set dist.dir
Must set build.classes.dir
Must set dist.javadoc.dir
Must set build.test.classes.dir
Must set build.test.results.dir
Must set build.classes.excludes
Must set dist.jar
.
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxhartrobert670
Broncos/build.xml
Builds, tests, and runs the project Broncos.
Broncos/manifest.mf
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
Broncos/nbproject/build-impl.xml
Must set src.dir
Must set test.src.dir
Must set build.dir
Must set dist.dir
Must set build.classes.dir
Must set dist.javadoc.dir
Must set build.test.classes.dir
Must set build.test.results.dir
Must set build.classes.excludes
Must set dist.jar
...
Spring tutorial for beginners - Learn Java Spring Framework version 3.1.0 starting from environment setup, inversion of control (IoC), dependency injection, bean scopes, bean life cycle, inner beans, autowiring, different modules, aspect oriented programming (AOP), database access (JDBC), Transaction Management, Web MVC framework, Web Flow, Exception handling, EJB integration and Sending email etc.
Flashnoden Jani Karhusen esitys Verkkokauppa-Akatemian aamiaistilaisuudessa. Esityksessä avattiin Verkkokauppa-Akatemian konseptia ja kerrottiin samalla Flashnoden palvelusta verkkokauppiaille.
Paytrail – Näin saat verkkomaksupainikkeet ja kaikki muut maksutavat verkkoka...Paytrail
Esittely Paytrailin perinteisestä maksupalvelusta. Miten se toimii ja mitä maksutapoja se sisältää? Miten saat pankkipainikkeet ja kaikki maksutavat verkkokauppaasi?
Webinar: Spring Framework - Introduction to Spring WebMVC & Spring with BigData Edureka!
The free webinar on Spring Framework titled "Spring Framework - Introduction to Spring WebMVC & Spring with BigData" was conducted by Edureka on 18th November 2014
1. Introduction to Web Services
2. Web Service Architecture
3. What are Web Services?
4. Why are Web Services?
5. The base of WS
6. What is SOAP?
7. What is WSDL?
8. How to test a web service?
9. Examples
This document provides step by step instructions on how to achieve dependency injection using dagger 2. The code is written in java. The code content is courtesy of Coding In Flow - You can check out this channel for in-depth explanation. https://www.youtube.com/watch?v=ZZ_qek0hGkM&list=PLrnPJCHvNZuA2ioi4soDZKz8euUQnJW65
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxcurwenmichaela
Broncos/build.xml
Builds, tests, and runs the project Broncos.
Broncos/manifest.mf
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
Broncos/nbproject/build-impl.xml
Must set src.dir
Must set test.src.dir
Must set build.dir
Must set dist.dir
Must set build.classes.dir
Must set dist.javadoc.dir
Must set build.test.classes.dir
Must set build.test.results.dir
Must set build.classes.excludes
Must set dist.jar
.
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxhartrobert670
Broncos/build.xml
Builds, tests, and runs the project Broncos.
Broncos/manifest.mf
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
Broncos/nbproject/build-impl.xml
Must set src.dir
Must set test.src.dir
Must set build.dir
Must set dist.dir
Must set build.classes.dir
Must set dist.javadoc.dir
Must set build.test.classes.dir
Must set build.test.results.dir
Must set build.classes.excludes
Must set dist.jar
...
Goal The goal of this assignment is to help students understand the.pdfarsmobiles
Goal: The goal of this assignment is to help students understand the use of JUnit to test Java
code.
Description: In this assignment you will create a set of unit tests, to test the behavior of the code
written for Assignment 1. To keep things consistent, please use the solution to assignment 1
provided by the instructor. You can find the solution on TRACS, under Resources >
Assignment-related material > Assignment
Solution
s.
A unit test is an automated piece of code that invokes a unit of work in the system and then
checks a single assumption about the behavior of that unit of work. A unit of work is a single
logical functional use case in the system that can be invoked by some public interface (in most
cases). A unit of work can span a single method, a whole class or multiple classes working
together to achieve one single logical purpose that can be verified.
Think of unit testing as a way to test the behavior of the code (or parts of the code) written,
without actually having to run the program. For example, in the case of assignments 1, assume
that the front-end (console user interface) part of the program and the back-end part of the
program (dealership database management) are written by two different developers. How would
the developer of the back-end be able to ensure that the code he/she has written does what it is
supposed to do without having access to the front-end?
A good unit test is:
• Able to be fully automated
• Has full control over all the pieces running.
• Can be run in any order, if part of many other tests
• Runs in memory (no DB or File access, for example)
• Consistently returns the same result (You always run the same test, so no random numbers, for
example.)
• Runs fast
• Tests a single logical concept in the system
• Readable
• Maintainable
• Trustworthy (when you see its result, you don’t need to debug the code just to be sure)
In this assignment, you are asked to create JUnit tests to test the classes and methods written for
assignment 1. First you should consider testing the behavior of theses classes/methods under
normal operation scenarios. For example, to test the method findCar(String vin) of the class
Dealership, you may need to create a test method, which creates a mock Car object and adds it to
the carList before the method findCar can be called to search for it. To ensure that everything
worked as planned, you can then search for the car using its VIN and see if the correct car is
found. Mock objects can be created either in the same test method or before any test methods are
run, using the @BeforeClass annotation.
Subsequently, you can consider creating test cases for unusual scenarios, e.g. when a certain
input or behavior is expected to cause an exception to be thrown, or when a user input is not as
expected.
At the end create a TestRunner class, which has a main method that runs the unit tests that you
have created, and prints out the test results.
Tasks:
1. Implement the JUnit tests to test only the.
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Matt Raible
JavaScript MVC Frameworks are all the rage these days. They’ve taken the web development world by storm. This session explores the various features of the three hottest JavaScript MVC frameworks: AngularJS, Ember.js and React.js. It also compares client-side templating vs. server-side templating and how well each framework supports Isomorphic JavaScript (code that can run both client-side and server-side). Finally, it ranks each framework on 10 different criteria using Yevgeniy Brikman’s framework scorecard.
Video on InfoQ: https://www.infoq.com/presentations/comparing-angular-ember-react
This document is about how to Write a CRUD App with Spring Boot Jpa or jdbc. a related example for this document is on github with the following address :
https://github.com/ghorbanihamid/SpringBoot_AOP_JPA_Example
Neoito — Design patterns and depenedency injectionNeoito
Dependency injection is a software design pattern that allows someone to remove hard-coded dependencies and makes it possible to change them. Dependencies can be injected to the object via the constructor or via defined method or a setter property.
Faiz Mohamed Haneef is currently the CEO and Chief Technology Architect at Neoito. He's a former Architect at Lowe's, Hallmark and Infosys.
Given at TechMaine's Java Users Group on Feb 26 2008
Why do we need another build tool when we already have Ant? By focusing on convention over configuration, Maven allows you to declaratively define how your project is built, which reduces a lot of the procedural code that you'd need to implement in every build file if you were using Ant. This, along with Maven's built-in management of repositories for project dependencies, allows you to streamline your build process. Ultimately Maven can reduce the amount of time that would otherwise be wasted hunting down jar files and fiddling with boilerplate build scripts.
This presentation covers Maven's core concepts. It introduces the Plugin architecture, and explain how the most popular plugins are used. It also covers the POM concept and how it relates to dependency tracking and repositories.
Who does *really* do Test-Driven Development? Probably only a small minority. The presentation shows what code leads to complex tests and what you have to consider to make writing tests much easier - because not doing TDD is no excuse for not having tests at all.
This is a document showing how Arduino can be used to control lights, fans or other electrical devices using a smart phone. We hare used Arduino UNO with HC-05 bluetooth module. Here we operate LED lights. This is helpful to initially understand how to deal with Arduino and bluetooth. In my next project I will show to operate 230v current to opearte lights and fans at our home.
Operating electrical devices with PIR sensor. No coding, No controllerSantosh Kumar Kar
Operating electrical device with PIR Sensor. We don't need any coding or any controller. The sensor will send signal to the relay and relay will operate the devices.
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
The Indian economy is classified into different sectors to simplify the analysis and understanding of economic activities. For Class 10, it's essential to grasp the sectors of the Indian economy, understand their characteristics, and recognize their importance. This guide will provide detailed notes on the Sectors of the Indian Economy Class 10, using specific long-tail keywords to enhance comprehension.
For more information, visit-www.vavaclasses.com
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
1. Beginning of Spring Part - 1 Author: Santosh Kumar Kar santosh.bsil@yahoo.co.in
2. Who This Tutor Is For? This tutor is for them who just start learning Springs. After going through this session, you will have the basic understandings of Spring Framework. You will able to write small applications using Spring. Also you can understand other complicated Spring projects after going through this session. I would suggest you to refer other good Spring books and tutors to understand Springs in depth. Remember, you can understand only the basics of Springs through this tutor which will be helpful to go depth into Springs. You can also download the source code of the examples from Download Links available at http://springs-download.blogspot.com/ Good Luck… Santosh
3. Introduction: In many books or sites, you will find about Spring that Spring supports inversion of control (IOC) and that it is a lightweight framework. You might be confused, what is inversion of control (IOC)? What is the purpose of using IOC? Why this feature is desirable?
12. Problem: There is a well known car racing computer game –NeedForSpeed. I have taken this example because most of us had played this game. You can Google if you want to know about this game ;)… In this game, there are the participants use varieties of cars, such as Ferrari Jaguar McLaren Ford Each type of car do have their own specifications say grip, accelerator, speed etc. Now let’s write a program for this game. There will be 1 generic class having common behavior. All the above different cars must inherit the common behavior of this generic class. We will name the generic class as:- NeedForSpeedCar which should be an interface. Other car classes such as Ferrari, Jaguar, McLaren, Fordetc. must implement that interface.
13. The generic class which contains the declaration of the common behavior of all the cars. This is NeedForSpeedCar.java //NeedForSpeedCar.java package spring.test.santosh.game; public interface NeedForSpeedCar{ String startEngine(); String accelerate(); } Now we do have variety of cars. The specification of Ferrari is different from Jaguar and McLaren. Similarly McLaren specification is different from other cars. So each variety of car do have it's own implementaton. So let's see the implementation of those cars.
14. //Ferrari.java package spring.test.santosh.game; public class Ferrari implements NeedForSpeedCar{ public String startEngine(){ return ("Start engine of your Ferrari Car"); } public String accelerate(){ return ("Accelerate and run fast your Ferrari Car"); } } //Jaguar.java package spring.test.santosh.game; public class Jaguar implements NeedForSpeedCar{ public String startEngine(){ return ("Start engine of your Jaguar Car"); } public String accelerate(){ return ("Accelerate and run fast your Jaguar Car"); } }
15. //McLaren.java package spring.test.santosh.game; public class McLaren implements NeedForSpeedCar{ public String startEngine(){ return ("Start engine of your McLaren Car"); } public String accelerate(){ return ("Accelerate and run fast your McLaren Car"); } } //Ford.java package spring.test.santosh.game; public class Ford implements NeedForSpeedCar{ public String startEngine(){ return ("Start engine of your Ford Car"); } public String accelerate(){ return ("Accelerate and run fast your Ford Car"); } }
16. The Race is going to be started. So let’s write that class… //Race.java package spring.test.santosh.game; public class Race{ public void startRace(){ //You choose your car-Ferrari NeedForSpeedCarmyracingcar= new Ferrari(); System.out.println(myracingcar.startEngine()); System.out.println(myracingcar.accelerate()); } } class Race has a dependency to class Ferrari The class Race has a dependency to class Ferrari. Now the car modules are ready. The race is ready. Let’s ask the Participant to start the race. The participant is ready to use Ferrari.
17. // Participant.java package spring.test.santosh.game; public class Participant{ public static void main(){ //You choose your car-Ferrari Racerace = new Race(); race.startRace(); } } Compile all the programs. And run Participant. The output would be: Now it looks pretty good. The Participant run the car Ferrari. See the next slide for what is the problem here…………………………………………
18. The participant wants to use the another car: McLaren McLaren is best for grip so he chosed this car for the race. But hey… Ohhhhnooooooooooo.... It's not really pretty good because of the Problem here is:the object of new Ferrari is hard coded. So to use McLaren, it should be: NeedForSpeedCarmyracingcar = new Ferrari(); NeedForSpeedCarmyracingcar = new McLaren(); So at any instance the participant wants to choose another car, it needs the code change in Race.java. If the participant wants to change to Fordfrom McLaren, then it must be: NeedForSpeedCarmyracingcar = new McLaren(); NeedForSpeedCarmyracingcar = new Ford();
19.
20. asetter MethodSo let’s restructure the classes. You need to follow few steps to work with Spring IOC.
21. Step 1: Add property for the object you need to inject and write setter method. //Race.java package spring.test.santosh.game; public class Race{ NeedForSpeedCarmyracingcar; public void setMyracingcar(NeedForSpeedCarmyracingcar){ this.myracingcar= myracingcar; } public void startRace(){ //You don’t create the object of any car type//NeedForSpeedCarmyracingcar = new Ferrari(); System.out.println(myracingcar.startEngine()); System.out.println(myracingcar.accelerate()); } } Newly added. Through the setter method the object will be injected into Race class. Now we need Spring Framework to provide the Dependent Injection into the class Race. So to use Spring, download the Spring Framework from http://www.springsource.org/download After you download set the library files into the classpath.
22. Step 2: Create the Spring Configuration XML file. This will contain the entries for the dependency injection. The object will be referred as a bean. We can give any name for this XML. Here we will name as: SpringConfig.xml <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="race" class="spring.test.santosh.game.Race"> <property name="myracingcar"> <ref local="ferrari"/> </property> </bean> <bean id="ferrari" class="spring.test.santosh.game.Ferrari" /> <bean id="ford" class="spring.test.santosh.game.Ford" /> <bean id="mclaren" class="spring.test.santosh.game.McLaren" /> <bean id="jaguar" class="spring.test.santosh.game.Jaguar" /> </beans> myracingcar is the property in Race.java. Through the setter method the object is injected into Race.java You can change the ref as per the car chosen by the participant from the below bean id list. These are the objects injected dynamically. The objects are created by IOC container and injected into Race.java
23. Step 3: Write the client. It must use the config springconfig.xml. packagespring.test.santosh.race.game; importorg.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; publicclassParticipant{ publicstaticvoid main(String args[]){ ApplicationContextctx = newFileSystemXmlApplicationContext("springconfig.xml"); Race race = (Race) ctx.getBean("race"); race.startRace(); } } The instance of Ferrari will be created. Now run Driver and see the output…
24. Now we will change the springconfig.xml to choose McLaren car instead of Ferrari. We will not touch any of the java file… And we will see the output after that… <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="race" class="spring.test.santosh.game.Race"> <property name="myracingcar"> <ref local="mclaren"/> </property> </bean> <bean id="ferrari" class="spring.test.santosh.game.Ferrari" /> <bean id="ford" class="spring.test.santosh.game.Ford" /> <bean id="mclaren" class="spring.test.santosh.game.McLaren" /> <bean id="jaguar" class="spring.test.santosh.game.Jaguar" /> </beans> Now ref is changed to "mclaren" from "ferrari". Output after you runDriver.class
25. To download the source code project for this example, you can choose the link*: NeedForSpeed.zip (Standalone Application) *athttp://springs-download.blogspot.com
26.
27. Bean factory methods for accessing application components.And many more… Now we will see how ApplicationContext is used to load the file resources. Here we are loading the Spring Config file -springconfig.xml
28.
29. collects all the bean id’s as defined in springconfig.xml. Say: race, ferrari, ford, McLaren.
30.
31. ApplicationContextinDifferent Applications/java Frameworks Till now we learned how we configure the Spring IOC (Independent Injection) by configuring the XML configuration file. So in the example you can notice the below line in Participant.java: ApplicationContextctx = newFileSystemXmlApplicationContext("springconfig.xml"); Here we are creating the object of FileSystemXMLApplicationContext by providing the XML name as argument. Our application is a stand-alone application and so simply we could use new FileSystemXMLApplicaitonContext(<XML file path>). Also this class constructor is helpful to create the Spring application context for test harness or unit testing. But there are different applications say Web application such as servlets/jsp's, Enterpriseapplications such as EJBs with Java Frameworks such as Struts, JSF etc. So in this section we will see how we can configure Springs IOC and how we will get the ApplicationContext in client.
32. Servlet andSprings I hope you are good in writing the Servlet and JSP application. So here I am not going to put how to build the servlet application and deploy it in the server. Just recall the directory structure in your servlet project: Now we will see where we can store our spring config XML file and how it could be accessible in the servlet classes. Note: It is very important that you don’t be confused this example with Springs MVC. We will see the Spring MVC latter. So now you concentrate how you will get the Spring ApplicationContext object in Servlet.
33. Achieving Springs Application Context in Servlet You can get the ApplicationContext of Spring in Servlet in 3 ways: Through new ClassPathXmlApplicationContext("<relative path of config XML>") Through new XmlWebApplicationContext() Through WebApplicationContextUtils.getWebApplicationContext(ServletContext);
34. Using ClassPathXmlApplicationContext The ClassPathXmlApplicationContextconstructor searches the given XML file from the classes folder in WEB-INF folder. Just you need to follow some basic steps. step 1: Create the spring config XML file. step 2: Name that file whatever you want. For example, in our example we named as: myspringconfig.xml step 3: Put this xml file in WEB-INF/classes folder while youare deploying. (If you use any editor like Eclipse, just put the XML in src folder, so when you build your project, it will automatically generate the same copy of XML along with the .class files in WEB-INF/classes folder.) Step 4: In servlet you can simply create the object of ClassPathXmlApplicationContextby passing the file relative path in constructor. E.g. ApplicatonContextctx = new ClassPathXmlApplicationContext("spring/test/santosh/config/myspringconfig.xml"); Herespring.test.santosh.configis a package created and stored the myspringconfig.xmlin this package. Let’s see the servlet example.
35.
36. The Spring Configfile – myspringconfig.xml will also remain unchanged. But you create a new packagespring.test.santosh.config and place this XML there.
37.
38. In the service (doPost) method, get the Bean public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Race race = (Race) ctx.getBean("race"); PrintStream out = new PrintStream(response.getOutputStream()); race.startRace(out); } Output To download the source code for this project for this example, you can choose the link*: NeedForSpeedServletOne.zip (Using ClassPathXmlApplicationContext) *athttp://springs-download.blogspot.com
39. UsingXmlWebApplicationContext The XmlWebApplicationContextconstructor searches the applicationContext.xmlfile fromthe WEB-INF folder where the web.xml is located. See the constructor, you don’t pass the XML file name. So to get the context you simply use as: XmlWebApplicationContextctx = new XmlWebApplicationContext(); ServletContextservletContext = servletConfig.getServletContext(); ctx.setServletContext(servletContext); ctx.refresh(); Race race = (Race) ctx.getBean("race"); XML File searches the applicationContext.xml from WEB-INF folder and then loads the bean classes. To download the source code for this project for this example, you can choose the link*: NeedForSpeedServletTwo.zip (Using XmlWebApplicationContext) *athttp://springs-download.blogspot.com
40. UsingWebApplicationContextUtils.getWebApplicationContext(ServletContext) When you use WebApplicationContextUtils.getWebApplicationContext(servletContext), you need to add ContextLoaderListener in web.xml as: <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> And when you use ServletContextservletContext = config.getServletContext(); ctx= WebApplicationContextUtils.getWebApplicationContext(servletContext); Race race = (Race) ctx.getBean("race"); XML File searches the applicationContext.xml from WEB-INF folder and then loads the bean classes.
41. So now you understood that, you can use ApplicationContextctx= WebApplicationContextUtils.getWebApplicationContext(ServletContextservletCtx); For that you need to add the ContextLoaderListenerclass in web.xml under the tag <listener> To download the source code for this project for this example, you can choose the link*: NeedForSpeedServletThree.zip (Using WebApplicationContextUtils) *athttp://springs-download.blogspot.com
42.
43.
44. And the second is, adding the parameters in <context-param> TAG with param-name as contextConfigLocation.xml.<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/springconfig.xml, /WEB-INF/racingcar.xml </param-value> </context-param>
45. Here you need not worry on updating/changing the XML file names in the java file such as ParticipantServlet.java. When you add any extra more spring config xml, just you need to update in web.xml under the tag <param-value> as shown in the previous slide. To download the source code for this project for this example, you can choose the link*: NeedForSpeedServletFour.zip (Using multiple spring config XMLs) *athttp://springs-download.blogspot.com
46.
47. Do you have Questions ? Please write to:santosh.bsil@yahoo.co.in