The first day of Spring's study

Keywords: Java Spring xml Session

  • With Ioc and Aop as the core, Spring provides a variety of application technologies such as the presentation layer spring MVC and the persistent layer Spring JDBC. It also integrates many well-known third-party frameworks and class libraries in the open source world, making it the most widely used open source framework for JavaEE enterprise applications.
  • Advantages of Spring:
  1. Convenient decoupling and simplified development;
  2. Support for Aop programming;
  3. Support for declarative transactions;
  4. Convenient program testing;
  5. Convenient integration of various excellent frameworks;
  6. Reduce the difficulty of using the JavaEE API;
  7. Spring source code is an example of classic learning;
  • Spring architecture: all based on core container Core Container

  • Compile-time dependencies: JDBC cannot compile without importing dependent packages, which are MySQL drivers.That is, the com.mysql.jdbc.Driver () dependency package was not found when registering the driver;
  • Coupling: Dependencies between programs, including: 1. Dependencies between classes; 2. Dependencies between methods;
  • Decoupling: Reduce the dependency between programs, should be done in actual development, compile-time dependency, run-time dependency;
  • Ideas for decoupling:
  1. Use reflection to create objects instead of the new keyword, Class.forName("fully qualified class name").
  2. Instead of writing directly to death, read the configuration file to get the full class name of the object to be created, and then create the object through reflection.
  • Decoupling method:

Mode 1: Decouple using engineering mode: (Create a factory for Bean objects to create Service and dao objects)

1. Define the full class name of a configuration file, bean.properties configuration service and dao layer.

Configuration:

      accountService=com.itheima.service.impl.IAccountServiceImpl
      accountDao=com.itheima.dao.impl.IAccountImpl

 

2. Reflect to create objects by reading the contents of the configuration file

BeanFactory Factory Class:

 3 import java.io.FileNotFoundException;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.util.Enumeration;
 7 import java.util.HashMap;
 8 import java.util.Map;
 9 import java.util.Properties;
10 
11 /**
12  * Create a factory for Bean objects
13  * Bean:In Computer English, there is the meaning of reusable components
14  *
15  * It is the one that creates the service and dao objects
16  *
17  * 1.Define a profile configuration service and dao
18  *      What to configure: Unique flag = Fully qualified class name (key=value form)
19  * 2.Reflect to create objects by reading from the configuration file
20  */
21 public class BeanFactory {
22     //Define a properties object
23     private static Properties properties = new Properties();
24 
25     //Define a map,Used to store objects we create, called containers
26     private static Map<String,Object> beans;
27 
28     //Using static code blocks as Properties Object Assignment
29     static {
30 
31         try {
32             //Obtain properties Stream object of file
33             InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
34             properties.load(is);
35             beans = new HashMap<String, Object>();
36             //Remove all from configuration file key
37             Enumeration keys = properties.keys();
38             //Traversal Enumeration
39             while (keys.hasMoreElements()){
40                 //Take out each key
41                 String key = keys.nextElement().toString();
42                 //according to key Obtain value
43                 String beanPath = properties.getProperty(key);
44                 //Reflection Create Object
45                 Object value = Class.forName(beanPath).newInstance();
46                 //hold key and value Store in container
47                 beans.put(key,value);
48             }
49         } catch (FileNotFoundException e) {
50             e.printStackTrace();
51         } catch (IOException e) {
52             e.printStackTrace();
53         } catch (IllegalAccessException e) {
54             e.printStackTrace();
55         } catch (InstantiationException e) {
56             e.printStackTrace();
57         } catch (ClassNotFoundException e) {
58             e.printStackTrace();
59         }
60     }
61 
62     /**
63      * Gets a bean object based on the name of the bean, where the object is a single object
64      * @param beanName
65      * @return
66      */
67     public static Object getBean(String beanName){
68         return beans.get(beanName);
69     }
70 }

 

 

* Objects created using factory mode and stored using Map collections as containers create a single object that we need.(Single object: only created once, members in the class are initialized once, which is efficient and generally has no definition of member variables. If you want to define variables, they are also within the method.Multiple Objects: Each time a new object is created, it is less efficient to execute than a single object, so that members of the class are initialized each time)

 

Mode 2: Use Spring's Ioc to control inversion (giving the right to create objects to the framework is an important feature of the framework, which includes Dependent Injection (DI) and Dependent Lookup (DL))

Introduction to Spring

Get core container objects and how to get bean objects based on IDS

 

/**
 * Simulate a presentation layer for invoking the business layer
 */
public class Client {

    /**
     * Get the core container of springIoc and get the object by id
     *
     * ApplicationContext Three common implementation classes
     * ClassPathXmlApplicationContext,It can load a configuration file under a class path, requiring that the configuration file must be under a class path and cannot be loaded if not (more commonly)
     * FileSystemXmlApplicationContext,It can load configuration files in any path to the disk, but with access
     *
     *
     *
     * AnnotationConfigApplicationContext,It is used to read annotations and create containers
     * @param args
     */
    public static void main(String[] args) {

        //1.Get Core Container Objects
        ApplicationContext ac =  new ClassPathXmlApplicationContext("bean.xml");
        //2.according to id Query acquisition bean object
        IAccountService accountService = ac.getBean("accountService", IAccountService.class);
        IAccountDao accountDao = (IAccountDao) ac.getBean("accountDao");
        System.out.println(accountService);
        System.out.println(accountDao);
}
}

 

 

* bean.xml 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--Give object creation to spring To manage id Name of the object to be created  class To create new Fully qualified class name of object-->
    <bean id="accountDao" class="com.itheima.dao.impl.IAccountImpl"></bean>

    <bean id="accountService" class="com.itheima.service.impl.IAccountServiceImpl"></bean>
</beans>

 

 

 

  • Questions raised about the two interfaces of the core container:

ApplicationContetx: When creating a core container, the strategy for creating objects is to load them immediately, that is, create configuration objects (single objects) in the configuration file as soon as the configuration file is read.

BeanFactory: When creating a core container, the strategy for creating objects is to use delayed loading, that is, when an object is acquired based on its id and when it is actually created (multiple objects).

  • There are three ways to create a bean object:
<!--Three ways to create bean s-->

    <!--
    First, create it using the default constructor, which cannot be created without it
    -->
    <bean id="accountService" class="com.itheima.service.impl.IAccountServiceImpl" scope="prototype"
    init-method="init" destroy-method="destroy">
    </bean>

    <!--
    Second, create objects using methods in a common factory (create objects using methods in a class and store them in the spring container)
     -->
    <!--<bean id="instanceFactory" class="com.itheima.factory.InstanceFactory"></bean>-->
    <!--<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>-->

    <!--
    Third, create objects using static methods in the factory (create objects using static methods in a class and store them in the spring container)
    -->
    <!--<bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="getAccountService"></bean>-->

 

 

 

  • Scope of the bean: <bean>scope property value: singleton-singleton (default), prototype-multiple, request: request request request scope in the web, session: session scope in the web, global-session: cluster environment session scope (global session)
  • Life cycle of bean s:
  1. The life cycle of a single object is the same as that of a core container.
  2. Multiple objects are created for us by the spring framework when we use them. Objects are always alive as long as they are in use and are garbage collected by the JVM virtual machine when they are not used for a long time.
  • Dependency injection in Spring is designed to maintain dependencies, referring to bean.xml

    bean.xml

<?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">

    <!--Using constructor injection -->
    <bean id="accountService" class="com.itheima.service.impl.IAccountServiceImpl">
        <constructor-arg name="name" value="test"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="date" ref="now"></constructor-arg>
    </bean>

<!--Configure a date object Date Type is not a basic data type, so first reflect and create Date Object storage Ioc Core container, then use ref Attribute Receive--> <bean id="now" class="java.util.Date"></bean> <!--Use set Method Injection More common ways--> <bean id="accountService1" class="com.itheima.service.impl.IAccountServiceImpl1"> <property name="name" value="test1"></property> <property name="age" value="19"/> <property name="date" ref="now"/> </bean>
<!--Injection of complex types/The injection structure tags of the collection type are interchangeable. List Structure set: list,array,set Labels can be generic, Map Structure set: map,props Tags can be generic--> <bean id="accountService2" class="com.itheima.service.impl.IAccountServiceImpl2"> <property name="myStrs"> <array> <value>aaa</value> <value>bbb</value> <value>ccc</value> </array> </property> <property name="myList"> <list> <value>aaa</value> <value>bbb</value> <value>ccc</value> </list> </property> <property name="mySet"> <set> <value>aaa</value> <value>bbb</value> <value>ccc</value> </set> </property> <property name="myMap"> <map> <entry key="testA" value="aaa"></entry> <entry key="testB"> <value>bbb</value> </entry> </map> </property> <property name="myProperties"> <props> <prop key="testC">ccc</prop> <prop key="testD">ddd </prop> </props> </property> </bean> </beans>

Posted by pkellum on Mon, 19 Aug 2019 09:44:40 -0700