Spring Framework Learning 1

Source: Internet
Author: User

Read Catalogue

      • First, spring overview
  • Core container:
  • Spring Context:
  • Spring AOP:
  • Spring DAO:
  • Spring ORM:
  • Spring Web Module:
  • Spring MVC Framework:
      • Second, instantiate spring container                                                           
      • Third, create JavaBean objects with spring container                                   
    • 1, constructor instantiation                           &NBS P                          ,         &NB Sp                        
    • 2, using static Factory method instantiation                              ,         &NB Sp                                
    • 3, instance factory instantiation                    /                                     ,         &NB Sp                  
      • Four, IOC app for container                           &NB Sp                                
    • 4.1) Set Injection
    • 4.2) using constructor parameters to implement dependency property injection
    • 4.3. Automatic attribute injection with automatic assembly

Back to top one, spring overview

The Spring framework is a layered architecture consisting of 7 well-defined modules. The Spring modules are built on top of the core container, and the core container defines how the beans are created, configured, and managed, as shown in 1.

Figure 1. 7 modules of the Spring framework

Each module (or component) that makes up the Spring framework can exist separately or be implemented in conjunction with one or more other modules. The functions of each module are as follows:

Back to TopCore Container:

The core container provides the basic functionality of the Spring framework. The main component of the core container is Beanfactory, which is the implementation of the factory pattern. The beanfactory uses the inversion of control (IOC) pattern to separate the application's configuration and dependency specifications from the actual application code.

Back to TopSpringContext:

The spring context is a configuration file that provides contextual information to the spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internationalization, checksum scheduling.

Back to TopSpring AOP:

The Spring AOP module integrates aspect-oriented programming functionality directly into the spring framework through configuration management features. Therefore, it is easy to enable any object managed by the Spring framework to support AOP. The spring AOP module provides transaction management services for objects in spring-based applications. By using Spring AOP, you can integrate declarative transaction management into your application without relying on EJB components.

Back to TopSpring DAO:

J The DBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the number of exception codes that need to be written (such as opening and closing connections). Spring DAO's JDBC-oriented exception conforms to the common DAO exception hierarchy.

Back to TopSpring ORM:

The Spring framework inserts several ORM frameworks, providing ORM object-relational tools, including JDO, Hibernate, and IBatis SQL Map. All of these conform to Spring's common transaction and DAO exception hierarchies.

Back to TopSpring WebModule:

The Web context module is built on top of the application context module and provides the context for Web-based applications. Therefore, the Spring framework supports integration with Jakarta Struts. The Web module also simplifies the process of working with multipart requests and binding request parameters to domain objects.

Back to TopSpring MVCFrame:

The MVC framework is a full-featured MVC implementation of building WEB applications. With the policy interface, the MVC framework becomes highly configurable, and MVC accommodates a large number of view technologies, including JSP, Velocity, Tiles, IText, and POI.

Back to top second, instantiate the spring container

2.1 Create a new Web project Spring-demo

2.2. Import the Spring core package

2.3. Import the Applicationcontext.xml file into SRC and create a new package Com.spring.demo

2.4, import JUnit, Project right click Properties---->java Build path---->libraries----->add Library----->JUNIT4---> Next--->finish

2.5, create a new JUnit Test case class,

2.6, instantiate container, get ApplicationContext profile address, create ApplicationContext object incoming get configuration address, console print out instantiation container information

2.7, the console prints out the message The following information indicates that the container was instantiated successfully

Org[email protected]3c1d332b:startup Date [Wed Nov 16:23:19 CST 2016]; Root of context Hierarchy

Back to top third, create a JavaBean object with the spring container back to top 1, instantiate with a constructor

<beanid= "CalendarObj1" class= "Java.util.GregorianCalendar" ></bean>

1.2) in the TestCase called Getbean Get configuration file Bean, Create Bean Object Instance

Calendar CR = Ac.getbean ("CalendarObj1", Calendar.class);

See Console information instantiated successfully

Calendarobj1:java.util.gregoriancalendar[time=1478679801551,arefieldsset=true,areallfieldsset=true,lenient= True,zone=sun.util.calendar.zoneinfo[id= "Asia/shanghai", Offset=28800000,dstsavings=0,usedaylight=false, Transitions=19,lastrule=null],firstdayofweek=1,minimaldaysinfirstweek=1,era=1,year=2016,month=10,week_of_year= 46,week_of_month=2,day_of_month=9,day_of_year=314,day_of_week=4,day_of_week_in_month=2,am_pm=1,hour=4,hour_of_ Day=16,minute=23,second=21,millisecond=551,zone_offset=28800000,dst_offset=0]

Back to top 2, instantiate using static Factory method

2.1) add <bean id= "CalendarObj2" class= "Java.util.GregorianCalendar" to the configuration file factory-method= " GetInstance "></bean>

2.2) is added in the TestCase test class testing method

Calendar Cr2 = Ac.getbean ("CalendarObj2", calendar.class);       System.out.println ("CalendarObj2:" +cr2);

2.3 look at the console .

Calendarobj2:java.util.gregoriancalendar[time=1478679801586,arefieldsset=true,areallfieldsset=true,lenient= True,zone=sun.util.calendar.zoneinfo[id= "Asia/shanghai", Offset=28800000,dstsavings=0,usedaylight=false, Transitions=19,lastrule=null],firstdayofweek=1,minimaldaysinfirstweek=1,era=1,year=2016,month=10,week_of_year= 46,week_of_month=2,day_of_month=9,day_of_year=314,day_of_week=4,day_of_week_in_month=2,am_pm=1,hour=4,hour_of_ Day=16,minute=23,second=21,millisecond=586,zone_offset=28800000,dst_offset=0]

Instantiation succeeded

Back to top 3, instance factory instantiation

3.1) Add in the Applicationcontext.xml configuration file

<!--instance Factory instantiation--        <bean id= "calendarObj3" class= "Java.util.GregorianCalendar" ></bean>        <bean id= "Dateobj" factory-bean= "CalendarObj3" factory-method= "GetTime" ></bean>

3.2) in the test class testing method increases

Date date = Ac.getbean ("Dateobj", date.class);    System.out.println ("calendarObj3:" +date);

3.3 JUnit test, control output

calendarobj3:wed Nov 16:23:21 CST 2016

Instantiation succeeded

Back to top four, the IOC application of the container returns to the top of the4.1)set injection

Set mode injection can be implemented by invoking the set method of the bean after it is invoked without a constructor or a parameterless static factory method to instantiate the bean.

4.1.1) Add in config file

<!--data source setter injection--><bean id= "DataSource" class= "Com.spring.dao.JDBCDataSource" ><property name= " Driver "value=" Com.mysql.jdbc.Driver "></property><property name=" url "value=" Jdbc:mysql://localhost : 3306/test?useunicode=true&amp;characterencoding=utf-8 "></property><property name=" username " Value= "root" ></property><property name= "password" value= "" >123456</property></bean>

4.1.2) writes the Jdbcdatasource class, which encapsulates the method of managing database Connections getconnection (), which requires database connection parameters before this method executes: Database driver, connection URL, user name and password, Here is the Jdbcdatasource code

View Code

4.1.3) uses spring to implement the creation of the Jdbcdatasource object, and then uses set injection to inject the database parameters into the Jdbcdatasource so that the getconnection () method can be called normally to get the database connection.

4.1.4) TestCase Test connection method

@Test public    void Testjdbcdatasource () throws sqlexception{        String conf = "Applicationcontext.xml";        ApplicationContext ac = new Classpathxmlapplicationcontext (conf);        Jdbcdatasource JDS = Ac.getbean ("DataSource", jdbcdatasource.class);        Connection cn = jds.getconnection ();        System.out.println (CN);    }

4.1.5) Console output

[Email protected]

Indicates that a database connection has been obtained

Back to top 4.2) using constructor parameters to implement dependency property injection

4.2.1) First build a user table

CREATE TABLE ' user ' (  ' id ' int ') not NULL auto_increment,  ' name ' varchar (CHARACTER SET UTF8 DEFAULT null,
    ' phone ' varchar default NULL,  ' password ' varchar (CHARACTER SET UTF8 default null,  ' gender ' varchar (10) CHARACTER SET UTF8 default NULL,  PRIMARY KEY (' id ')) engine=innodb auto_increment=3 default charset=latin1;

4.2.2) Creating a User entity class

View Code

4.2.3) Create interface Userdao, write a method that queries the user by user name Finduserbyname (String name)

Package Com.spring.dao;import Com.spring.entity.user;public Interface Userdao {public    User finduserbyname (String name);}

4.2.4) Create Mysqluserdao implementation Userdao,

View Code

4.2.5) Spring supports instantiating bean methods with constructor injection parameters, as long as the constructor parameter is added to the configuration file constructor-arg,spring automatically creates an instance of the Bean object with the parameter constructor.

<bean id= "Userdao" class= "Com.spring.dao.MysqlUserDao" >            <constructor-arg index= "0" ref= "DataSource" ></constructor-arg>        </bean>

4.2.6) Write a Testfinduserbyname method in the test class

@Test public    void Testfinduserbyname () {        String con = "Applicationcontext.xml";        ApplicationContext ac = new  classpathxmlapplicationcontext (con);        Userdao Userdao = Ac.getbean ("Userdao", userdao.class);        User user = Userdao.finduserbyname ("Lisi");        SYSTEM.OUT.PRINTLN (user);            }

4.2.7) Console correctly outputs user information stating the success of the constructor injection

User [id=2, Name=lisi, phone=110, password=321654, Gender=1]

4.2.8) failure may not add a parameter constructor in Mysqluserdao

back to top 4.3. Automatic attribute injection with automatic assembly

4.3.1) Create a Userloginservice class, write a login method login (), the method relies on the Finfuserbyname () method

View Code

4.3.2) The Autowire property has four ways of default is no, (1). ByName (2) Bytype, (3) Constuctor, (4) AutoDetect,

4.3.3) Modify the configuration file, add the configuration

<!--automatic assembly--         

4.3.4) Write test method Testuserlogin ()

@Test public    void Testuserlogin () {        String con = "Applicationcontext.xml";        ApplicationContext ac = new classpathxmlapplicationcontext (con);        Userloginservice US = Ac.getbean ("Userloginservice", userloginservice.class);        User user = Us.login ("Lisi", "321654");        SYSTEM.OUT.PRINTLN (user);    }

4.3.5) Console output

User [id=2, Name=lisi, phone=110, password=321654, Gender=1]

Automatic assembly Instructions Successful

Spring Framework Learning 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.