Code Monkey home page Code Monkey logo

spring-starter's Introduction

Setup

  1. download Eclipsed Jave EE distrubition from http://www.eclipse.org/
  2. download Java SE JDK http://www.oracle.com/technetwork/java/javase/overview/index.html
  3. download lastest release of Spring libs from http://repo.spring.io/release/org/springframework/spring/
  4. download tomcat from http://tomcat.apache.org/
  • link local tomcat server in Eclipse at server tab
  • Eclipse - Window - Perspective - Open Perspective - Java
  • add Spring libraries JAR to your project
    • Copy Spring /libs/xxx.jar to project /lib folder
    • Project Properties - Java Build Path - Libraries - Add JARs - add all of them

spring-demo-1

1.Basic JAVA app

2.Basic Spring app

  • config in applicationContext.xml
  • remember import springframework JARs b/c ClassPathXmlApplicationContext is essentail here

3.Dependency Injection - Constructor Injection

  • update service bean in applicationContext.xml
  • setup constructor injection in applicationContext.xml

4.Dependency Injection - Setter Injection

  • setup setter injection in applicationContext.xml
  • convention: invoke set + property name(capital case) method

5.Dependency Injection - Literal Value Injection

  • setup literal value injection in applicationContext.xml
  • value attribute in property tag will be injected when invoking set + property name method

6.Literal Value Injection in Another Properties File

  • make literal values maintainable in one single file

7.Bean Scope

  • default bean scope is singleton, i.e. application container always returns same instance. - stateless object
  • set scope="prototype" in beanScope-applicaitonContext.xml file, thus different instances returned. - stateful object

8.Bean Lifecycle Methods

  • Convention:
    • The methods should be public void
    • The methods should be no-arg, meaning they shouldn't accept any method arguments
  • Life Cycle:
    1. Container started
    2. Bean instantiated
    3. Dependencies Injected
    4. Internal Spring Processing
    5. Your Custom Init Method
    6. Bean Is Already For Use
    7. Container Is Shut Down
    8. Your Custom Destroy Method
    9. STOP
  • Cavet:

Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. --- This also applies to both XML configuration and Annotation-based configuration.

spring-demo-anotations

  • Spring libraries
  • javax.annotation-api-1.3.1.jar
  • applicationContext.xml

copy from last demo or search internet

1.Annotation - Explicit Component Name

  • annotation minimizes the config than xml files
  • setup context-component-scan in applicationContext.xml
  • @Component annotataion in business code

2.Annotation - Default Component Name

  • default bean id is class name in camel case

3.Annotation - Constructor Injection

  • Spring will automatically scan our package since we've set up in applicationContext.xml
  • @Component the Service class
  • @Autowired the constructor

4.Annotation - Setter Injection

  • @Autowired a setter method inside

5.Annotation - Method Injection

  • every method can be annotated by @Autowired to inject dependency

6.Annotation - Field Injection

  • apply directly to a field
  • no need setter method for the field

7.Annotation - Qualifier

  • multiple Services implement same Interface
  • decide which one to inject via Qualifier
  • Cavet:

the special case of when BOTH the first and second characters of the class name are upper case, then the name is NOT converted. RESTFortuneService --> RESTFortuneService Behind the scenes, Spring uses the Java Beans Introspector to generate the default bean name. Here's a screenshot of the documentation for the key method. Java Beans Introspector

8.Annotation - Literal Value Injection

  • set up context:property-placeholder in applicationContext.xml
  • @Value(${})

9.Annotation - Bean Scope - Singleton

  • default bean scope is singleton
  • same as @Scope("singleton")

10.Annotation - Bean Scope - Prototype

  • Spring Container returns different beans

11.Annotation - Bean Life Cycle Methods

  • @PostConstruct as init-method
  • @PreDestroy as destroy-method
  • remember prototype bean won't invoke destroy-method, b/c bean doesn't record prototype beans
  • javax.annotation in not default included in JAVA 9

NOTICE if got errors when using @PostConstruct and @PreDestroy Java >= 9, javax.annotation has been removed from its default classpath. Download the javax.annotation-api-1.2.jar and add it to your project as for the Spring jar files

12.Java Source Code Configuration

  • Create a Java Class and annotate as @Configuration
  • Add component scanning support: @ComponentScan (optional)
  • Read Spring Java configuration class
  • Retrieve bean from Spring container

13.Java Code Config - Inner Defined Bean

  • define bean inside the Java code configuration

14.Java Code Config - Load Properties

  • Create Properties File
  • Load Properties File in Spring Config
  • Reference values from Properties File

spring-mvc-demo

1.Set up

  • New - Dynamic Web Project
  • manually paste lastest Spring libraries to WebContent/WEB-INF/lib
  • manually paste additional libraries to WebContent/WEB-INF/lib
  • xml configuration files in WebContent/WEB-INF
    • spring-mvc-demo-servlet.xml
    • web.xml

configure the Spring Dispatcher Servlet using all Java Code (no xml): https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-container-config

2.Spring MVC - Controller & View

  • annotate class with @Controller
  • @Controller inherits from @Component ... supports scanning(according to base-package setting)
  • @Requestmapping("/") maps a path to a method name
  • the method should return view name which will be assembled with prefix suffix in config
  • finnaly, Run as Server

How to Clean Server Cache: stop the tomcat in Server tab, right click the server and select Clean..., right click the server again and select Clean Tomcat Work Directory...

How to Clean Eclipse Cache: select the top-level menu option, Project -> Clean ..., be sure your project is selected and click OK, restart Eclipse

3.Spring MVC - Handle Form Data

  • a tag as hyperlink
  • HTML form action
  • get param from query string

4.Spring MVC - Add Attribute to Model

  • model.addAttribute("foo", obj/string/...) in controller method
  • ${foo} in view jsp file

Bouns:

  • config assets resource in Spring
  • Deploy app to Tomcat as a Web Application Archive(WAR) file
    1. stop tomcat in Eclipse
    2. Right Click project, and select Export > WAR file
    3. input a file name, 'myapp.war' for example
    4. start tomcat outside of Eclipse
    5. move the new WAR file to /path/install/tomcat/webapps/
    6. visit http://localhost:8080/myapp

5.Spring MVC - Annotation RequestParam

  • @RequestParam("foo") String bar parse the foo value in queryString and evalute it to bar

6.Spring MVC - Annotation Request Parent Mapping

  • Annotate the Controller with @RequestMapping gives a route scope, resolving ambiguous mapping

7.Spring MVC - Form Tag

  • Official Doc
  • visit localhost:8080/spring-mvc-demo/student/showForm

8.Spring MVC - Form Select Tag

  • hard code options in JSP

9.Spring MVC - Form Options Tag

  • read data from model layer
  • use it in view layer

10.Spring MVC - Literal Value Injection

  • set up context.xml header
  • util:properties

11.Spring MVC - Form Radiobutton Tag

12.Spring MVC - Form Checkbox Tag

Spring MVC - Form Validation

set up our development environment

  • download hibernate-validation JAR from http://hibernate.org/validator/releases/6.0/
  • copy dist/xxx.jar and dist/lib/required/xxx.jar to /WEB-INF/lib

1.required field

  • Add validation rule to Customer Class
  • Display error messages on HTML form
  • Perform validation in the Controller class
  • Update confirmation page

1.1.Pre-processing with @InitBinder

  • treat the input only contains whitespaces as invalid

2.validate number range: min, max

3.validate using regular expression

4.validate number as required

  • Convertion Type Issue Int -> String
  • Use Integer Type instead of Int

5.handle string input for interger field

  • Override error code with messages.properties file

6.custom validation

  • new package com.luv2code.springdemo.validation
  • new annotation CourseCode
    • Contraint
    • Target
    • Retention
  • new CourseCodeConstraintValidator implements ConstraintValidator

hibernate-tutorial

Set Up Development Environment

  1. MySQL

install (remember the temporary password)

export PATH=$PATH:/usr/local/mysql/bin
sudo /usr/local/mysql/support-files/mysql.server start
mysql -u root -p (input the temporary password)
set password = password('123456');
  1. Database Table

run the following sql scripts

  • /scripts/01-create-user.sql
  • /scripts/02-student-tracker.sql
  1. Hibernate ORM

copy /lib/required/xxx.jar to /hibernate-tutorial/lib

  1. MySQL Connector/J
  • download platform independent zip file
  • copy /mysql-connector-java-x.y.z.jar to /hibernate-tutorial/lib
  1. Add JARs

For Java >=9, download the following jar files, since java.xml.bind has been removed

Project Properties - Java Build Path - Libraries - Add JARs

  1. Add hibernate configuration file
  • src/hibernate.cfg.xml
  1. Annotate Java class
  • @Entity
  • @Table(name="tbl")
  • @Id
  • @Column(name="column")
  1. Develop Java code to perform database operations

hb-01-one-to-one-uni

hb-02-one-to-one-bi

hb-03-one-to-many

hb-eager-vs-lazy

hb-04-one-to-many-uni

hb-05-many-to-many

spring-starter's People

Contributors

chengcyber avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.