cool hit counter SSH framework tour-spring (1)_Intefrankly

SSH framework tour-spring (1)


spring.jpg

1.Introduction to Spring Framework


Spring is an open source lightweight Java development framework that solves the problem of too much coupling between the business logic layer and other layers , it can be used not only on Java EE , for Java SE can also be used . The name of the game is that the emergence of Spring is considered to bring a spring to software development, its layered architecture allows Spring framework with other frameworks such as Struts2, Hibernate, the three together called SSH framework. Spring is more than just a framework; the inversion of control (IOC) and cutter-oriented programming (AOP) design ideas are its essence.

Three-tier structure for Java EE development in Spring.

  • web layer: Spring MVC
  • service layer: Bean management
  • dao layer: Spring's JDBCTemplate integration with other persistence frameworks, such as : Hibernate

2.Concepts in spring


2.1 AOP (cut-face oriented programming)

This one is in Strust2 It is also mentioned in,Struts2 The interceptor is an implementation of cut-oriented programming, Extend functionality on top of the original without modifying the source code, Rather, it is through configuration file。

2.2 IOC (Inversion of Control)

Leaving the creation of objects to Spring, rather than creating them by new, is also consistent with the software development High cohesion and low coupling The design philosophy of minimizing object-to-object call relationships.

3.Building a Spring Framework

3.1 Prepare the relevant jar packages for Spring

The download button is not prominently displayed on the Spring framework's official website; here is a list of Spring versions Download Address I downloaded the zip archive for version 4.3.9. After unpacking, the docs folder is Spring's API documentation and development specifications, the libs folder is Spring's jar packages and source code, and the scheme folder is Spring's constraints file. In the libs folder, every third jar package is a group, including the development jar package, the documentation, and the source code.

3.2 Import the relevant jar packages for Spring

The four jar packages spring-beans, spring-context, spring-core, and spring-expression in the libs folder, as well as a jar package for logging, commons-logging, will appear in the console if this jar package is not imported java.lang.ClassNotFoundException error, but this package is not in the Spring framework and belongs to a development component in the Apache project, which is also provided here as a Download Address import these five jar packages in the lib folder of the java web project.

3.3 Use cases for Spring

physical category

    package cc.wenshixin.entity;
    
    public class Student {
        
        public void study()
        {
            System.err.println(" Learning in progress。。。");
        }
    }

configuration file

Spring of configuration file Name of the harmony The position is not fixed, However, it is recommended that it be placed directly on the src The directory facilitates harmony of other frameworks configuration file unified management, Also the official recommendation of configuration file The name is applicationContext.xml, But you can also set your own configuration file name (of a thing)。 harmony Struts2、Hibernate in the framework of the configuration file with different types of constraint files, The first two are dtd bind, And the latter is scheme bind。 with respect toscheme The binding template for the, It can be found in this address (look on the lean back section), or you can copy the basic template constraints below.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="
                    http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd">
      <bean id="student" class="cc.wenshixin.entity.Student"></bean>
    </beans>

Test category

Using the IOC (Inversion of Control) technique (the underlying implementation of IOC is described in detail below), the object creation is left to Spring to complete, plus the class id name in the configuration file to return the created object, which is the design idea of the factory pattern.

    package cc.wenshixin.test;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import cc.wenshixin.entity.Student;
    
    public class Test1 {
        
        @Test
        public void test01()
        {
    //1. Load spring's configuration file and create objects based on the configuration file
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
             //2. Get the objects created in the configuration
            Student student = (Student) context.getBean("student");
            student.study();
        }
    }

4.bean management in Spring


4.1 The underlying implementation principle of IOC

The underlying IOC is implemented through the dom4j parsing xml file, factory design pattern, and reflection mechanism, as shown in the following diagram.

IOC Underlying Principles.png

4.2 bean Three ways to instantiate an object

- The first one is created using the class's unrefined constructor (emphasis added)

The use case above uses this way of creating objects, which is relatively simple and is often used in development. Note that there should be a constructor with no parameters in the entity class, otherwise Spring cannot create the entity class object and an exception occurs. If there is a constructor with parameters in the entity class, manually patch the constructor method without parameters to make it easier for Spring to call.

  • The second one is created using a static factory

Use a factory class that creates static methods that return objects

physical category Code as above

Factory category

    package cc.wenshixin.factory;
    
    import cc.wenshixin.entity.Student;
    
    public class StudentFactory1 {
        public static Student getStudent()
        {
            return new Student();
        }
    }

configuration file

  <!--  Using a static factory to create -->
  <bean id="studentFactory1" class="cc.wenshixin.factory.StudentFactory1" factory-method="getStudent"></bean>

Test category

    @Test
    public void test02()
    {
//1. Load spring's configuration file and create objects based on the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         //2. Get the objects created in the configuration
        Student student = (Student) context.getBean("studentFactory1");
        student.study();
    }
  • third type Using the instance factory to create

Use a factory class that creates ordinary methods that return objects

physical category Code as above

Factory Class Code

    package cc.wenshixin.factory;
    
    import cc.wenshixin.entity.Student;
    
    public class StudentFactory2 {
        public Student getStudent()
        {
            return new Student();
        }
    }

configuration file

  <!--  Using the instance factory to create -->
  <bean id="studentFactory2" class="cc.wenshixin.factory.StudentFactory2"></bean>
  <bean id="stud" factory-bean="studentFactory2" factory-method="getStudent"></bean>

Test category

    @Test
    public void test03()
    {
//1. Load spring's configuration file and create objects based on the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         //2. Get the objects created in the configuration
        Student student = (Student) context.getBean("stud");
        student.study();
    }

4.3 Common attributes in the bean tag

  • id attribute: gives the bean a name. The id attribute can be named arbitrarily, but cannot contain special symbols, and is used to value the configuration object based on the id attribute.
  • class attribute: the full path to the class in which the object was created
  • name attribute: same function as the id attribute, but the name attribute can contain special symbols in its name
  • scope attribute.
    • 1.singleton Default value of property, single object
    • 2.prototype several targets
    • 3.request Create the object and place it in the request field
    • 4.session Create the object and place the object in the session field
    • 5.globalSession establish targets include targets put together globalSession in

The first two values of the scope attribute are commonly used, and the last few are known.

test (machinery etc) singleton property value, the default can be left out, modifying the code in the test class above as follows.

    @Test
    public void test01()
    {
//1. Load spring's configuration file and create objects based on the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         //2. Get the objects created in the configuration, Using the singleton pattern, both targets quoted address same
        Student s1 = (Student) context.getBean("student");
        Student s2 = (Student) context.getBean("student");
        System.out.println(s1);
        System.out.println(s2);
    }

test (machinery etc) prototype attribute value, the code to modify the configuration file is as follows.

    <bean id="student" class="cc.wenshixin.entity.Student" scope="prototype"></bean>

Execute the above again Test category code, Observe the two targets quoted address different, That is, it creates multiple targets。

4.3 Property injection in bean

So-called property injection is setting values to an object's properties when the class object is created, and is somewhat loftily named.

There are three general ways of attribute injection

  • 1. use set method injection
    public class Student{
      private String name;
      public setName(String name){
        this.name = name
      }
    }
    //set method injection
    Student student = new Student();
    student.setName(" Simon");
  • 2.Injection using a referenced constructor
    public class Student{
      private String name;
      public Student(String name){
        this.name = name
      }
    }
     // Constructor injection
    Student student = new Student(" Simon");
  • 3.Using interface injection
public interface Dao{
  public void setName(String name);
}
public class DaoImpl implements Dao{
  private String name;
  public void setName(String name){
    this.name = name;
  }
}

however, in Spring in, Only the first two methods are supported, i.e. set method injection harmony Constructor injection, pass (a bill or inspection) configuration file come to be made targets is created with the targets The assignment of the relevant attributes of the。

- use set method injection properties

Modify the entity class to

    package cc.wenshixin.entity;
    
    public class Student {
        private String name;

        public void setName(String name) {
            this.name = name;
        }
        
        public String getName() {
            return name;
        }
    }

configuration file

  <!--  Using the way to inject properties -->
  <bean id="student" class="cc.wenshixin.entity.Student">
    <property name="name" value=" Simon"></property>
  </bean>

test (machinery etc) approach

    @Test
    public void test01()
    {
//1. Load spring's configuration file and create objects based on the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         //2. Get the objects created in the configuration
        Student s = (Student) context.getBean("student");
        // importation configuration file The value of the attribute injected in the
        System.out.println(s.getName());
    }
  • Injecting properties using a parameterized constructor

Entity class adds reference constructor method

configuration file Modify to

  <!--  Injecting properties using a parameterized constructor -->
  <bean id="student" class="cc.wenshixin.entity.Student">
    <!--  Injection using reference construction -->
    <constructor-arg name="name" value=" small red"></constructor-arg>
  </bean>

test (machinery etc) Same method as above

  • empty into targets Properties of the type

Create a servic class and a dao class, and get the object of the dao in the service, which is common in Java Web development.

The sample code is as follows.

Entity category as above

dao class

    package cc.wenshixin.entity;
    
    public class Dao {
        public void insert()
        {
            System.out.println("Dao Insert student data。。。");
        }
    }

service class

    package cc.wenshixin.entity;
    
    public class Service {
         // Define to type attribute
        private Dao dao;
         // Generate set method
    
        public void setDao(Dao dao) {
            this.dao = dao;
        }
        
        public void add()
        {
            System.out.println("Service Add Operation");
            dao.insert();
        }
    }

configuration file

property In the tab.name The property value is service The name of the property in the class thatref attribute value in the configuration of the dao id attribute value, you can't write here value property now, as it is an object and cannot be property injected.

  <!--  configureservice harmonydao targets -->
  <bean id="dao" class="cc.wenshixin.entity.Dao"></bean>
  <bean id="service" class="cc.wenshixin.entity.Service">
    <property name="dao" ref="dao"></property>
  </bean>

test (machinery etc) approach

    @Test
    public void test03()
    {
//1. Load spring's configuration file and create objects based on the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         //2. Get the objects created in the configuration
      Service service = (Service) context.getBean("service");
      service.add();
    }
  • P namespace Property Injection

Add to the constraints in the configuration file xmlns:p="http://www.springframework.org/schema/p"

physical category The default constructor is required in the harmony attribute corresponding to theset approach

package cc.wenshixin.entity;

public class Student {
    private String name;
    
    public Student() {

    }

    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
}

configuration file

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             add comments to text: add intop namespace
            xmlns:p="http://www.springframework.org/schema/p"
            xsi:schemaLocation="
                    http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd">
       <!-- p Namespace injection -->
       <bean id="student" class="cc.wenshixin.entity.Student" p:name=" old king"></bean>
    </beans>

test (machinery etc) approach

    @Test
    public void test01()
    {
//1. Load spring's configuration file and create objects based on the configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         //2. Get the objects created in the configuration
        Student s = (Student) context.getBean("student");
        System.out.println(s.getName());
    }

Recommended>>
1、Douche mahjong cheat apple version hulu mahjong cheat fork turn attack tonggu mahjong cheat
2、Chinas first superhighway doesnt have to worry about speeding and can enjoy autonomous driving
3、Worlds Smallest Angular Resolution MEMS Solid State Lidar Publicly Demonstrated Sutem Polytron Seizes the High Ground of Autonomous Driving
4、Python for quick word cloud graph generation this is the most detailed tutorial bar none
5、The first thing you need to do is to get a good idea of what youre doing

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号