Diese Präsentation wurde erfolgreich gemeldet.
Die SlideShare-Präsentation wird heruntergeladen. ×

Spring framework in depth

Nächste SlideShare
Spring Core
Spring Core
Wird geladen in …3

Hier ansehen

1 von 63 Anzeige

Weitere Verwandte Inhalte


Ähnlich wie Spring framework in depth (20)

Weitere von Vinay Kumar (20)


Aktuellste (20)

Spring framework in depth

  1. 1. By- Vinay Kumar
  2. 2.  Introduction  Injection  Aspect Dependency Oriented Programming  Bean Factory  Wiring Objects  Spring MVC  Spring DAO
  3. 3. Introduction  Spring Framework  is a J2EE Framework  that provides a lightweight container  for dependency injection  and Aspect oriented Programming (AOP) Now what was that, again?
  4. 4. DI or IOC  Dependency injection or Inversion of control  Alternative to Service Locator Locate your own dependencies Let the framework do the dirty job for you
  5. 5. AOP  Aspect oriented programming  Cross cutting concerns  Transaction, Security and Logging requirements
  6. 6. BeanFactory      Interface BeanFactory BeanFactory creates beans getBean() method Implementation classes like the XmlBeanFactory Methods:  getBean()  isSingleton()  getType()  getAliases()  containsBean() This is how a BeanFactory looks like
  7. 7. Using BeanFactory public static void main (String args []){ BeanFactory factory = new XmlBeanFactory (new FileInputStream (“bean-config.xml”)); MyBean mybean = (MyBean) factory.getBean (“myBean”); mybean.methodx(): } A Web Application may never need to use code such as the one shown above as the framework does it all for us.
  8. 8. ApplicationContext  Extends the BeanFactory  Adds the following methods:  getResource()  getMessage()
  9. 9. Wiring Objects  Spring provides for declarative wiring of objects  Declaring a bean  Declaring beans as singleton or prototype  Declaring init and destroy methods  Injecting values into beans properties  Injecting other beans as properties  Injecting arrays and collections as properties Spring book This book on Spring is marvelous ! Now I am a wiring expert too !
  10. 10. Declaring beans <beans> <bean id=“x” class=“y”/> </beans> When using the id attribute, special characters are not permitted. Spring therefore allows the use of an alternative attribute: name <bean name=“x” class=“y”/>
  11. 11. To singleton or not  Beans are instantiated as Singletons by default. This is how we can override the default : <beans> <bean id=“x” class=“y” singleton=“false”/> </beans>
  12. 12. Init and destroy  As Spring manages the bean lifecycle, it allows us to specify the init and destroy methods declaratively. <beans> <bean id=“x” class=“y” init-method=“a”/> <bean id=“p” class=“q” destroy-method=“b”/> </beans>
  13. 13. Alternative  Spring defines the following interfaces  InitializingBean  DisposableBean  Beans implementing these interfaces are assured that the methods defined in these interfaces are called back by Spring during initialization and destruction.  This is thus an alternative to the init and destroy method declaration in the config.xml
  14. 14. Dependency Injection  Spring allows for:  Setter based injection  Constructor based injection
  15. 15. Setter injection  Setter based injection allows us to inject values into bean properties through the setter methods.  These values may be  Primitive Types  Strings  Beans  Arrays  Collections  Property
  16. 16. Primitive Types <bean id=“x” class=“y”> <property name=“age”> <value>26</value> </property> </bean> This sets “26” to the property age
  17. 17. Strings <bean id=“x” class=“y”> <property name=“nm”> <value>val</value> </property> </bean> This sets “val” to the property nm <bean id=“x” class=“y”> <property name=“pq”> <value></value> </property> </bean> This sets an empty string “” to the property pq
  18. 18. Null values <bean id=“x” class=“y”> <property name=“nm”> <value><null/></value> </property> </bean>
  19. 19. Bean <beans> <bean id=“myClass” class=“demo.MyClass”> <property name=“display”> <ref bean=“a” /> </property> </bean> <bean id=“a” class=“util.TestClass”/> </beans>
  20. 20. Arrays and Lists <bean id=“x” class=“y”> <property name=“nm”> <list> <value>pqr</value> <value>xyz</value> <value>abc</value> </list> </property> </bean>
  21. 21. List of objects <beans> <bean id=“x” class=“y”> <property name=“nm”> <list> <ref bean=“a”/> <ref bean=“b”/> </list> </property> </bean> <bean id=“a” class=“p”/> <bean id=“b” class=“q”/> </beans>
  22. 22. Sets <bean id=“x” class=“y”> <property name=“nm”> <set> <value>pqr</value> <value>xyz</value> <value>abc</value> </set> </property> </bean> For a set consisting of beans use the <ref bean> tag
  23. 23. Maps <beans> <bean id=“x” class=“y”> <property name=“nm”> <map> <entry key=“k1”> <value>val1</value> </entry> <entry key=“k2”> <ref bean=“a” /> Spring limits the user to declare keys as Strings only </entry> </map> </property> </bean> <bean id=“a” class=“p”/> </beans>
  24. 24. Properties <beans> <bean id=“x” class=“y”> <property name=“nm”> <props> <prop key=“k1”>val1</prop> <prop key=“k2”>val2</prop> </props> </property> </bean> </beans>
  25. 25. Constructor injection Spring allows for injection via constructors Below is example of constructor based injection <beans> <bean id=“myClass” class=“demo.MyClass”> <constructor-arg> <value>42</value> </constructor-arg> </bean> </beans>
  26. 26. Constructor injection Spring allows for injection via constructors Below is example of constructor based injection for setting multiple arguments <beans> <bean id=“myClass” class=“demo.MyClass”> <constructor-arg index=“1”> <value>42</value> </constructor-arg> <constructor-arg index=“2”> <ref bean=“testClass”/> </constructor-arg> </bean> </beans>
  27. 27. Constructor injection - Advantage The data members of the class are set only once at the time of creation/instantiation of the object. There are no public setter methods that are exposed to the outside world and through which the state of an object can be changed. Thus the object is immutable.
  28. 28. Constructor injection - Disadvantage The xml declaration for constructor based injection is complex and the developer has to ensure that there are no ambiguities in the parameters
  29. 29. Autowiring  Spring has autowiring capabilities <beans> <bean id=“x” class=“y” autowire=“byName”> </bean> </beans> The dependencies need not be defined in the xml explicitly. With autowire by Name option if we ensure that the name of id in xml, and name of the properties in the java class matches then the Spring framework automatically invokes setter methods. Note: byName should be used with only setter based injection
  30. 30. Modules  Seven modules or packages
  31. 31. Spring Core  Dependency Injection  BeanFactory and ApplicationContext
  32. 32. Spring Web  Web utilities Spring tags for use in html/jsp  Multipart functionality  Integration with Struts framework In one application the struts can be used in web MVC layer and integrated with other Spring components in the application bigfile.xml part1.xml part2.xml part3.xml
  33. 33. Spring Web MVC  Controller  Validator
  34. 34. Life cycle of a request Spring Web MVC Handler Mapping 2 Request 3 1 Dispatcher Servlet Controller 4 ModelAndView 5 ViewResolver 6 View
  35. 35. Spring Web MVC 2 Request Handle Mapping 3 1 Dispatcher Servlet Controller 4 ModelAndView 5 ViewResolver
  36. 36. Life cycle of a Request 1. 2. 3. 4. 5. 6. 7. The client typically web browser send request (1) The first component to receive is DispatcherServlet. All the requests goes through single front controller servlet. DispacherServlet queries HandlerMapping. This is a mapping of URLs and Controller objects defined in configuration xml Dispatcher servlet dispatches request to Controller to perform business logic Controller returns the model and the view. The model is the data that need to be displayed in the view. The view is a logical name that is mapped to the .jsp file that will render the view. This is defined in the xml mapping file Controller send request to ViewResolver to resolve which .jsp to render for which view Finally the view is rendered
  37. 37. Configuring the Dispatcher Servlet Dispatcher servlet is MVC’s front controller. Like any servlet it must be configured in Spring application context Example: <servlet> <servlet-name>testapp</servlet-name> <servletclass>org.springframework.web.servlet.DispatcherServl et</servlet-class> <load-on-startup>1</load-on-startup> <servlet> Since the dispatcher servlet’s name is testapp the servlet will load the application context from a file named ‘testapp-servlet.xml’
  38. 38. Spring Web MVC - Controller There are following main Controller types  Abstract Controller  Simple Form Controller  Multi Action Controller All the above are implementation classes for the Controller Interface
  39. 39. Abstract Controller  This controller is used when the view/GUI has to be read only.  No data is entered in the screen Example public class ListCircuitsController extends AbstractController{ public ModelAndView handleRequestInternal(HttpServletRequest req,HttpServletResponse res){ Collection circuits=circuitService.getAllCircuits(); return new ModelAndView(“circuitList”,”circuits”, circuits); } The first argument “circuitList” is the name of the view to which the controller is associated. The second argument is the name of the model object which holds the third argument circuits object.
  40. 40. Declaring View Resolver View Resolver resolves the logical view name returned by controller to the jsp file that renders the view. Of the various view resolvers InternalResourceViewResolver is simplest for rendering jsp Example <!-- view-resolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResource ViewResolver"> <property name="prefix"> <value>/WEB-INF/ui/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <!-- /view-resolver -->
  41. 41. Mapping requests to Controllers SimpleUrlHandlerMapping is one of the straight forward Spring’s handler mapping. This maps the URL patterns to controllers. Example <bean id="urlMapping" class="org.springframework.web.servlet.handler.Simple UrlHandlerMapping"> <property name="urlMap"> <map> <entry key="/forum.do"> <ref bean="forumController" /> </entry> </map> </property> </bean> <!-- /UrlMapping -->
  42. 42. Simple Form Controller  This controller is used for GUI which have a data entry form to be filled in and submitted by the user.  The controller is responsible for –  Displaying the form for data entry  Validating data entered by the user  Redisplaying the form on error with error message  Submitting the data  Displaying the success page
  43. 43. Command Object  It holds the data that the user enters in the form/GUI
  44. 44. Simple Form Controller -code public class EnterCircuitDetailsController extends SimpleFormController{ public EnterCircuitDetails(){ setCommandClass(Circuit.class); } Protected void doSubmitAction(Object command) throws Exception{ Circuit circuit=(Circuit) command; circuitService.createCircuit(circuit); } Private CircuitService circuitservive; Public void setCircuitService(CircuitService circuitservice){ this.circuitService=circuitService; } }
  45. 45. Simple Form Controller -Configuration  The details of configuration of the view is as below: <bean id=“enterCircuitDetailsController" class=" com.circuit.mvc.CircuitDetailsController"> <property name=“circuitService" ref=“circuitService" /> <property name="formView"><value>circuitForm</value></property> <property name="successView"><value>circuitCreated.do</value></pr operty> </bean>
  46. 46. Simple Form Controller -explained  As per the above example EnterCircuitDetailsController displays a form for taking the details of the circuit that need to be created as well as processes the data that is entered.  The doSubmitAction() method handles form submission and takes details of the form from Circuit object  The doSubmitAction() does not return ModelAndView object and hence with this we will not be able to send any data to the view. If a particular view need to be displayed with some data in it we need to use the onSubmit() method instead.
  47. 47. Simple Form Controller -explained  SimpleFormController is designed to keep view details out of the controller’s code. The formView represents the logical name of the view that is to be displayed when the Controller gets a GET request or there are any errors on the form. The success view represents the logical name of the view to be displayed when form is submitted successfully. The view resolver will use this to render the actual view to the user.
  48. 48. Simple Form Controller  Below is an example of onSubmit method protected ModelAndView onSubmit(Object command, BindException errors) throws Exception { Circuit circuit = (Circuit) command; circuitService.createCircuit(circuit); return new ModelAndView(getSuccessView(),“circuit", circuit); }
  49. 49. Multi Action Controller  These controllers are used to handle multiple actions in a single controller. Each action is handled by a different method within the controller.  The specific method that needs to be called in the Action controller based on the type of resolver.  The below example shows that we are using methodName Resolver <bean id="multiactionController" class="com. mvc.ListCircuitsController"> <property name="methodNameResolver"> <ref bean="methodNameResolver"/> </property> </bean>
  50. 50. Multi Action Controller  There are two types of method name resolvers like ParameterMethodNameResolver and PropertiesMethodNameResolver. This will ensure that the appropriate method in the Multiaction Controller is called based on the parameter name passed in the request. The parameter name will need to be same as the method name in the MultiActionForm Controller. Below is the configuration that need to be done <bean id="methodNameResolver" class="org.springframework.web. servlet.mvc.multiaction.ParameterMethodNameResolver"> <property name="paramName"> <value>action</value> </property> </bean>
  51. 51. Multi Action Controller  Example: If we are accessing the URL “http://…/listCircuits.htm?action=circuitsByDate” the method name circuitsByDate() is called in the MultiActionController since we have configured the name resolver to be based on the parameter passed in the request.
  52. 52. Spring Web MVC-Validator  Spring provides a Validator Interface that is used for validating objects  For Example: In the example of a simple form controller in previous slides in which there is a command object “circuit” which needs to be validated or in other words we need to validate that the circuit details entered by the user are correct. In that case the class Circuit should implement the Validator interface
  53. 53. Spring Web MVC-Validator  Validator Interface has the following methods defined in it public interface Validator { void validate(Object obj, Errors errors); boolean supports(Class class); }
  54. 54. Spring Web MVC-Validator Code  Sample code below explains how Validator Interface is implemented to perform validations. We write a class ValidateCktDetails for validating circuit details entered by user public class CircuitValidator implements Validator { public boolean supports(Class class) { return class.equals(Circuit.class); } public void validate(Object command, Errors errors) { Circuit circuit = (Circuit) command; ValidationUtils.rejectIfEmpty( errors, “circuitType", "required. circuitType ", “Circuit Type is mandatory for creating a circuit"); }
  55. 55. Web MVC-Validator Code Explained  The framework uses support() method to check if the Validator can be used for a given class  The validate() methods can validate all the attributes of the object that is passed into validate() method and reject invalid values through Errors object
  56. 56. Spring Web MVC-Validator  The only other thing to do is to use the CircuitValidator with EnterCircuitDetailsController which can be done by wiring the bean <bean id=“enterCircuitDetailsController" class= "com.circuit.mvc.CircuitDetailsController"> <property name="validator"> <bean class="com.validate.mvc.CircuitValidator"/> </property> </bean>
  57. 57. Spring Web MVC  When a user enters the circuit details, if all of the required properties are set and circuit type is not empty, then EnterCircuitDetailsController’s doSubmitAction() will be called. However, if CircuitValidator rejects any of the fields, then the user will be returned to the form view to correct the errors.
  58. 58. Spring Context  Resource bundles  Event propagation  Bean Lookup
  59. 59. Spring ORM  Hibernate support- Spring provides integration with Object Relational mapping frameworks like Hibernate
  60. 60. Spring DAO  Transaction infrastructure  JDBC support  DAO support
  61. 61. Spring DAO-JDBC  Assuming that the persistence layer in an application is JDBC. In that case we need to use DataSourceTrnsactionManger which will manage transactions on a single JDBC Data Source  The source code explains the use of Transaction Manager. The transaction manager takes care of managing the transactions. <bean id="transactionManager" class="org.springframework.jdbc. datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean>
  62. 62. Spring DAO-JDBC  The dataSource property is set with a reference to a bean named datasource <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@</value> </property> <property name="username"> <value>test</value> </property> <property name="password"> <value>test</value> </property> </bean>

Hinweis der Redaktion

  • Life cycle of a RequestThe client typically web browser send request (1)The first component to receive is DispatcherServlet. All the requests goes through single front controller servlet.DispacherServlet queries HandlerMapping. This is a mapping of URLs and Controller objects defined in configuration xmlDispatcher servlet dispatches request to Controller to perform business logicController returns the model and the view. The model is the data that need to be displayed in the view. The view is a logical name that is mapped to the .jsp file that will render the view. This is defined in the xml mapping fileController send request to ViewResolver to resolve which .jsp to render for which viewFinally the view is rendered