1 / 26

Spring Framework

Spring Framework. Anti Orgla, Nortal AS. 08.04.2014. Web appication framework ? . How do you handle your requests ? How do you access your database ? How do you manage your session ? Code reuse ? Maybe it’s already been done ?. Web application f ramework.

corin
Télécharger la présentation

Spring Framework

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SpringFramework Anti Orgla, Nortal AS 08.04.2014

  2. Webappicationframework? • Howdoyouhandleyourrequests? • Howdoyouaccessyourdatabase? • Howdoyou manage yoursession? • Codereuse? • Maybeit’salreadybeendone?

  3. Web application framework • Typically frameworks provide libraries: • Database Access • Sessionmanagement • Requestmanagement • Transactionmanagement • UI Templates • Cache, Security, Ajax, WebServices, etc…

  4. Howtoget a String from DB? public static String getName(Connectioncon, int id){ Statement stmt = null; String query = "selectnamefrom user_infowhere id = ?"; try { stmt = con.createStatement(); stmt.setInt(1, id); ResultSetrs = stmt.executeQuery(query); if(rs.next()) { returnrs.getString("name"); }else{ return null; } } catch (SQLException e ) { //handletheexception } finally { if (stmt != null) { stmt.close(); } } }

  5. Easierway? public static String getName(int id){ return jdbcTemplate.queryForObject("select namefrom user_info where id = ?",String.class, id); }

  6. Spring Framework • One of themostpopular • Open source application framework • Veryflexible • Availablesince 2002 (v4.0 dets.2013) • Did I sayitisveryflexible?

  7. SpringFramework • Inversion of Control • DependencyInjection • staticvs runtime • abstractions vs implementations

  8. Dependency injection publicinterfaceUserDao { UsergetByUserName(Stringname); } @Repository publicclassJdbcUserDaoimplementsUserDao { publicUsergetByUserName(Stringname) { // load userfrom DB } } @Resource privateUserDaouserDao; Universal abstraction

  9. Dependency injection publicinterfaceUserDao { UsergetByUserName(Stringname); } @Repository publicclassJdbcUserDaoimplementsUserDao { publicUsergetByUserName(Stringname) { // load userfrom DB } } @Resource privateUserDaouserDao; One possible implementation. Spring will create and register it

  10. Dependency injection publicinterfaceUserDao { UsergetByUserName(Stringname); } @Repository publicclassJdbcUserDaoimplementsUserDao { publicUsergetByUserName(Stringname) { // load userfrom DB } } @Resource privateUserDaouserDao; Injectionis made asanabstraction

  11. IoC in Spring • Spring handles the infrastructure • (bean creation, dependency lookup and injection) • Developerfocuses on application specific logic • Youcandescribehowyourapplicationiscoupled, notcoupleityourself!

  12. XML based configuration • Bean can also be defined and injected in XML. <bean id="userDao" class="example.JdbcUserDao" /> <bean id="userService" class="example.UserService"> <property name="userDao" ref="userDao" /> </bean>

  13. MVC – Whatwasthat? http://java.sun.com/blueprints/patterns/MVC-detailed.html

  14. Model-View-Controller • Controller: executesbusinesslogic, dataactionsetc. Forms a modelobject and passes ittoviewforrendering • Model: objectforpassingdatabetweencontroller and view • View: takesmodeldatafromthecontroller and presentsittothe end user

  15. Model-View-Controller • Separation of differentlayers • An application might have more than one user interface • Different developersmay be responsible for different aspects of the application.

  16. Spring MVC • IoC again – framework handles the infrastructure, you focus on application specific things.

  17. Architecture - DispatcherServlet http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html

  18. Let’swritesome MVC! Code demo..

  19. Built-in conversion • There are some standard built-in converters. @RequestMapping("/foo") public String foo( @RequestParam("param1")intintParam, @RequestParam("param2")long longParam) { ...

  20. Type conversion • You can also define your own PropertyEditors • PropertyEditorSupportimplementsPropertyEditor

  21. Custom types publicclassDateRange { privateDatestart; privateDateend; publicDateRange(Date start, Date end) { this.start = start; this.end = end; } publicintgetDayDifference() { // calculate } }

  22. Custom type editor publicclassDateRangeEditorextendsPropertyEditorSupport { privateDateFormatdateFormat = newSimpleDateFormat("dd.MM.yyyy"); publicvoidsetAsText(String text) throwsIllegalArgumentException { String[] parts = text.split("-"); Date start = dateFormat.parse(parts[0]); Date end = dateFormat.parse(parts[1]); setValue(newDateRange(start, end)); } public String getAsText() { DateRangedateRange = (DateRange) getValue(); returndateFormat.format(dateRange.getStart()) + "-" + dateFormat.format(dateRange.getEnd()); } } String to custom type Custom type to String

  23. Register and use @Controller publicclassMyController { @InitBinder publicvoidinitBinder(WebDataBinderbinder) { binder.registerCustomEditor(DateRange.class, newDateRangeEditor()); } @RequestMapping(value="/dateRange") public String dateRange(@RequestParam("range") DateRange range) { ... } }

  24. Non-intrusive • Very important feature of a framework is non-intrusiveness. • Spring MVC normally lets you do stuff according to MVC pattern. • But it doesn’t prevent you from violating MVC if you really want to.

  25. Codeexamples.. Code demo..

  26. Sources of wisdom • Spring has great documentation: http://www.springsource.org/spring-framework#documentation • Java BluePrints - Model-View-Controllerhttp://www.oracle.com/technetwork/java/mvc-detailed-136062.html • Model-View-Controllerhttp://www.oracle.com/technetwork/java/mvc-140477.html • Inversion of controlhttp://en.wikipedia.org/wiki/Inversion_of_control

More Related