The way of basic learning of spring framework

Posted by noginn on Wed, 09 Feb 2022 13:48:15 +0100

1, IoC control reversal

  1. IoC control inversion, fully known as Inverse of Control, is a design concept
  2. The agent creates and manages the object, and the consumer obtains the object through the agent
  3. The purpose of IoC is to reduce the direct coupling between programs
  4. Add IoC container to manage objects in a unified way and make object association become weak coupling

2, DI dependency injection

  1. IoC is the design concept, the standard followed by modern programming and the macro goal
  2. DI(Dependency Injection) is a specific technical implementation and a micro implementation
  3. DI uses reflection technology to realize object injection in Java

3, The meaning of Spring

  1. Spring can be viewed from both narrow and broad perspectives
  2. In a narrow sense, Spring refers to the Spring framework (Spring Fremework)
1. Spring Framework is a one-stop solution to the complexity of enterprise development
2. Spring The core of the framework is IoC Container and AOP Aspect oriented programming
3. Spring IoC Responsible for creating and managing system objects and expanding functions on this basis
  1. Spring in a broad sense refers to the spring ecosystem

4, Spring IoC container responsibilities

  1. The control right of the object is handed over to a third party for unified management (IoC control)
  2. Using Java reflection technology to realize runtime object creation and Association (DI dependency injection)
  3. Improving maintainability and scalability of applications based on configuration

5, XML management object (Bean)

  1. Three configuration modes
    a. Configuring beans based on annotations
    b. Configuring beans based on Java code
    c. Configuring beans based on XML
    c1.applicationContext.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--bean Labels create objects using the default construction method-->
    <bean id="apple1" class="com.imooc.spring.ioc.entity.Apple">

    </bean>
    <!--Instantiate an object using the parameterized construction method-->
    <bean name="apple2" class="com.imooc.spring.ioc.entity.Apple">
        <constructor-arg name="title" value="Red Fuji"/>
        <constructor-arg name="color" value="gules"/>
        <constructor-arg name="origin" value="Europe"/>
        <constructor-arg name="price" value="19.8"/>
    </bean>

    <bean id="apple3" class="com.imooc.spring.ioc.entity.Apple">
        <constructor-arg index="0" value="Red Fuji"/>
        <constructor-arg index="1" value="Europe"/>
        <constructor-arg index="2" value="gules"/>
        <constructor-arg index="3" value="19.8"/>
    </bean>

    <!--Get objects using static factories-->
    <bean id="apple4" class="com.imooc.spring.ioc.factory.AppleStaticFactory"
          factory-method="createSweetApple"/>

    <!--Using factory instance method to obtain objects-->
    <bean id="factoryInstance" class="com.imooc.spring.ioc.factory.AppleFactoryInstance"/>
    <bean id="apple5" factory-bean="factoryInstance" factory-method="createSweetApple"/>
</beans>

c2. Create IoC container in XML mode

//Create an IoC container and create objects based on the configuration file
ApplicationContext context = newClassPathXmlApplicationContext("classpath:applicationContext.xml");
  1. Three ways to instantiate beans
    Object instantiation based on construction method
Instantiation of parameter names by construction method
<bean id="sweetApple" class="com.imooc.spring.ioc.entity.Apple">
 <!-- No, constructor-arg It means calling the default constructor instantiation -->
 <constructor-arg name="title" value="Red Fuji"/>
 <constructor-arg name="origin" value="Europe"/>
 <constructor-arg name="color" value="gules"/>
</bean>

Based on static factory instantiation

  <!--Get objects using static factories-->
    <bean id="apple4" class="com.imooc.spring.ioc.factory.AppleStaticFactory"
          factory-method="createSweetApple"/>
/**
 * Static factories create objects through static methods, hiding the details of creating objects
 */
public class AppleStaticFactory {
    public static Apple createSweetApple(){
        //logger.info("")
        Apple apple = new Apple();
        apple.setTitle("Red Fuji");
        apple.setOrigin("Europe");
        apple.setColor("gules");
        return apple;
    }
}

Factory instance based method instantiation

    <!--Using factory instance method to obtain objects-->
    <bean id="factoryInstance" class="com.imooc.spring.ioc.factory.AppleFactoryInstance"/>
    <bean id="apple5" factory-bean="factoryInstance" factory-method="createSweetApple"/>
/**
 * Factory instance method creation object refers to the process that IoC container instantiates the factory class and calls the corresponding instance method to create an object
 */
public class AppleFactoryInstance {
    public Apple createSweetApple(){
        Apple apple = new Apple();
        apple.setTitle("Red Fuji");
        apple.setOrigin("Europe");
        apple.setColor("gules");
        return apple;
    }
}

6, Get bean from IoC container

Apple sweetApple = context.getBean("sweetApple" , Apple.class);
perhaps
Apple sweetApple = (Apple)context.getBean("sweetApple");
---------------------------------------------------------------------- System.out.println(sweetApple.getTitle());

7, Difference between id and name

  1. id and name attributes are the same
    Both bean id and name are unique identifiers of the setting object in the IoC container
    Both are not allowed to duplicate in the same configuration file
    Both allow duplication in multiple configuration files, and the new object overwrites the old object

  2. Difference between id and name attributes
    id requirements are more stringent, and only one object id can be defined at a time (recommended)
    name is more relaxed, allowing multiple object IDs to be defined at a time
    Tips: the naming requirements of ID and name are meaningful and written according to the hump name

8, Path matching expression
1. Load a single configuration file

//Create an IoC container and create objects based on the configuration file
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

2. Load multiple configuration files

String[] configLocations = new String[{"classpath:applicationContext.xml","classpath:applicationContext-1.xml"};
ApplicationContext context = newClassPathXmlApplicationContext(configLocations);

3. Path expression

9, Object dependency injection

  1. Object dependency injection
    Dependency injection refers to the operation of assigning objects in the container to other objects by reflection at run time
    Injecting objects based on setter method
  <bean id="sweetApple" class="com.imooc.spring.ioc.entity.Apple">
        <!-- IoC The container automatically uses the reflection mechanism to call the runtime setXXX Method to assign a value to an attribute -->
        <property name="title" value="Red Fuji"/>
        <property name="color" value="gules"/>
        <property name="origin" value="Europe"/>
        <property name="price" value="19.8"/>
    </bean>

Using setter to realize object injection

    <bean id="lily" class="com.imooc.spring.ioc.entity.Child">
        <property name="name" value="Lily"/>
        <!-- utilize ref Inject dependent objects -->
        <property name="apple" ref="sweetApple"/>
    </bean>

Injecting objects based on construction method

Injection collection object

10, Detailed explanation of bean scope attribute

  1. bean scope property
    The bean scope attribute is used to determine when an object is created and scope
    The bean scope configuration will affect the number of objects in the container
    By default, bean s will be instantiated automatically after the IoC container is created, which is globally unique

2.scope usage

<bean id="bookDao"
 class="com.imooc.spring.ioc.bookshop.dao.BookDaoOracleImpl"
 scope="prototype" />



11, Configuring IoC containers based on annotations
1. Advantages based on annotation

   Get rid of cumbersome XML Formal bean Dependency injection configuration
   be based on"Declarative"Principle of,More suitable for lightweight modern enterprise applications
   Make the code more readable,R & D personnel have a better development experience

2. Three types of notes

   Component type annotation-Declare the functions and responsibilities of the current class
   Auto assembly annotation-Automatically inject objects according to attribute characteristics
   Metadata annotation -More detailed assistance IoC Annotation of container management object

3. Notes of four component types

@Component Component annotation,General notes,The class described by this annotation will be IoC Container management and instantiation
@Controller Semantic annotation,Indicates that the current class is MVC Controller class in application
@Service Semantic annotation,Description the current class is Service Business services
@Repository Semantic annotation,Description: the current class is used in the business persistence layer,Usually describe the corresponding Dao class

4. Turn on component scanning

<!--XML Configure open component scanning,To use annotations-->
<context:component-scan base-package="com.imooc">
 <context:exclude-filter type="regx" expression="com.imooc.exl.*/>
</context:component-scan>

12, Two types of automatic assembly annotation

Assemble by type
@Autowired Dynamically inject attributes by object type in container,from Spring Provided by institutions
@Inject be based on JSR-330(Dependency Injection for Java)standard, Other same@Autowired,But not supported required attribute

Assemble by name
@Named And@Inject Use together,JSR-330 standard,Auto assemble attributes by attribute name
@Resource be based on JSR-250 standard,Intelligent matching by name first and then by type

13, Metadata annotation

@Primary Multiple objects of the same type appear when assembling by type,Objects with this annotation are injected first
@PostConstruct description method ,amount to XML in init-method Configured annotation version
@PreDestroy description method ,amount to XML in destroy-method Configured annotation version
@Scope Sets the of the object scope attribute
@Value Inject static data into attributes
<!--notice Spring IoC Load properties file when container initializes-->
    <context:property-placeholder location="classpath:config.properties"/>

Topics: Java Spring