Day 6 learn to punch in (Spring: introduction, IOC theoretical basis, hellosppring, IOC object creation method, Spring configuration, dependency injection)

1.Spring

1.1 INTRODUCTION

  • Spring: Spring = = > brings spring to the software industry
  • In 2002, Rod Jahnson first launched the Spring framework prototype interface21 framework
  • In 2004, based on the interface 21 framework, the Spring framework was redesigned and released the official version of 1.0
  • Rod Jahnson is a doctor of musicology from the University of Sydney. His major is not computer
  • Spring concept: making the existing technology more practical is a hodgepodge in itself, integrating the existing framework technology

Official website: https://spring.io

Official download address: repo.spring.io

GitHub: https://github.com/spring-projects

Maven package:

  • Using Spring
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.5</version>
</dependency>
  • Spring integrates jdbc
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.5</version>
</dependency>

1.2 advantages

  • Spring is an open source free framework, container
  • Spring is a lightweight framework, non intrusive
  • Core features: control inversion IOC, aspect oriented AOP
  • Support for transaction and framework integration

In one sentence: Spring is a lightweight control inversion (IOC) and aspect oriented (AOP) container (framework)

1.3 composition

The Spring framework is a layered architecture consisting of seven well-defined modules.

The Spring module is built on top of the core container, which defines how bean s are created, configured, and managed.

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

  • **Core container: * * core container provides the basic functions of Spring framework. The main component of the core container is BeanFactory, which is the implementation of the factory pattern. BeanFactory uses the inversion of control (IOC) pattern to separate the configuration and dependency specifications of the application from the application code of the century.

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

  • **Spring AOP: * * through the configuration management feature, the spring AOP module directly inherits the aspect oriented programming functions into the spring framework. Therefore, it is easy for the spring framework to manage any object that supports AOP. The spring AOP module provides transaction management services for objects in spring based applications. By using spring AOP, declarative transaction management can be integrated into applications without relying on components.

  • **Spring DAO: * * the JDBC 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 amount of exception code that needs to be written (such as opening and closing connections). The JDBC oriented exceptions of spring DAO follow the general DAO exception hierarchy.

  • **Spring ORM: * * the spring framework inserts several ORM frameworks to provide ORM object relationship tools, including JDO, HIbernate and iBatis SQL Map. All of this follows spring's common transaction and DAO exception hierarchy.

  • **Spring Web module: * * the Web context module is built on the application context module and provides context for web-based applications. Therefore, the spring framework supports integration with Jakarta Struts. The web module also simplifies processing multipart requests and binding request parameters to domain objects.

  • **Spring MVC framework: * * MVC framework is a full-featured MVC implementation for building Web applications. Through the policy interface, the MVC framework becomes highly configurable. MVC accommodates a large number of view technologies, including JSP, Velocity, Tiles, iText and POI.

1.4 expansion

Spring Boot:

  • A rapidly developed scaffold;
  • Based on Spring Boot, you can quickly develop a single micro service;
  • The concept of constraint over configuration is used. Many integration schemes have been selected for you. You can't configure without configuration;

Spring Cloud:

  • Spring Cloud is implemented based on Spring Boot;
  • Spring Boot focuses on a single micro service individual that is fast and easy to integrate. Spring Cloud focuses on the overall service governance framework;
  • A large part of Spring Cloud is implemented based on Spring Boot. Spring Boot can be used independently of Spring Cloud for development projects, but Spring Cloud cannot be separated from Spring Boot and belongs to dependency.
  • Spring Boot plays a connecting role in Spring Cloud. To learn Spring Cloud, you must learn Spring Boot

Disadvantages of Spring: after developing for too long, it violates the original concept! Configuration is very cumbersome, known as "configuration hell!"

2.IOC theoretical basis

Create a new blank maven project

2.1 analysis and Implementation

1. Write a piece of code in the original MVC mode

(1) UserDao interface (dao layer)

public interface UserDao {
    public void getUser();
}

(2) UserDaoImpl implementation class

public class UserDaoImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("Get user data");
    }
}

(3) UserService interface (service layer)

public interface UserService {
    public void getUser();
}

(4) UserServiceImpl implementation class

public class UserServiceImpl implements UserService {
    //Associate dao layer objects in the service layer
    private UserDao userDao=new UserDaoOracleImpl();

    @Override
    public void getUser() {
        userDao.getUser();
    }
}

(5) Test (control layer)

public class MyTest {
    @Test
    public void getUser(){
        UserService userService = new UserServiceImpl();
        userService.getUser();
    }
}

2. The Dao layer adds interfaces, causing problems

(1) Add an implementation class of UserDao, UserDaoMysqlImpl:

public class UserDaoMysqlImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("Mysql get data");
    }
}

Next, if we want to use MySql, we need to modify the corresponding implementation in the service implementation class

public class UserServiceImpl implements UserService {    //Associate dao layer objects in the service layer and modify the new object private userdao userdao = new userdaooracleimpl()@ Override    public void getUser() {        userDao.getUser();    }}

(2) Suppose we add another UserDao implementation class UserDaoOracleImpl

public class UserDaoOracleImpl implements UserDao{    @Override    public void getUser() {        System.out.println("Oracle get data");    }}

To use Oracle, you also need to modify the corresponding new object implementation in the service implementation class

public class UserDaoOracleImpl implements UserService {    //Associate dao layer objects in the service layer and modify the new object private userdao userdao = new userdaooracleimpl()@ Override    public void getUser() {        userDao.getUser();    }}

Question:

  • If we have a large number of similar requirements and there are many implementation classes for an interface of dao layer, the user needs to modify the program (dao layer implementation class referenced by service layer)

  • Each change requires a lot of code modification. The coupling of this design is too high, which affects the whole body

3. Problem solving [ key points ]

Where we can use dao layer in the service layer, we do not implement it, but leave an interface and use set. Let's modify it in the code:

public class UserServiceImpl implements UserService {    //Associate the dao layer object private UserDao userDao in the service layer// [revolutionary change] the dao layer interface implementation class used in the service layer often changes, so instead of implementing it, an interface public void setuserdao (userdao userdao) {this. Userdao = userdao;}@ Override    public void getUser() {        userDao.getUser();    }}

Test:

@Testpublic void getUser(){    UserServiceImpl userService = new UserServiceImpl();    //Mysql implements userservice setUserDao(new UserDaoMysqlImpl());     userService. getUser();    // Oracle implements userservice setUserDao(new UserDaoOracleImpl());     userService. getUser();}

**Difference: * * fundamental changes have taken place

  • Previously, the program took the initiative to create objects, and the control was in the hands of the programmer (for example, the service layer refers to the implementation of dao layer implementation class objects)
  • After using set injection, the program is no longer active, but becomes a passive receiving object. Give the initiative to the caller. The program doesn't care how to create or implement it. It is only responsible for providing an interface.

This idea essentially solves the problem. We programmers no longer manage the creation of objects

The coupling of the system is greatly reduced, and you can focus more on the business, which is the prototype of IOC!

2.2 essence of IOC

  • Inversion of Control (IOC) is an idea (instead of specific implementation, it provides a set interface), and DI (dependency injection) is a method to implement IOC;
  • In programs without IOC, we use object-oriented programming. The creation of objects and the dependencies between objects are completely hard coded. In the program, the creation of objects is controlled by the program itself;
  • After the control is reversed, the creation of the object is transferred to a third party;
  • Inversion of control (IOC) even if the way to obtain dependent objects is reversed.

IOC is the core content of the Spring framework. It is perfectly implemented in many ways. It can be configured using XML or practical annotations. The new version of Spring can also implement IOC with zero configuration;

  • When initializing, the Spring container reads the configuration file first and stores the "create and organize objects" in the container according to the configuration file or metadata;
  • When the program is used, take out the required objects from the IOC container.

  • When configuring a Bean in XML, the definition information of the Bean is separated from the implementation;

  • The two can be integrated by annotation. The definition information of Bean is directly defined in the implementation class in the form of annotation, so as to achieve the purpose of zero configuration.

  • Inversion of control is a way to produce or obtain specific objects through description (XML or annotation) and through a third party.

  • In Spring, the IOC container implements control inversion. When implementing methods, it depends on injection (DI)

3.HelloSpring

3.1 import jar package

Note: spring needs to import commons logging for logging We use maven, which will automatically download the corresponding dependencies.

<!--Spring-webmvc--><dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-webmvc</artifactId>    <version>5.3.5</version></dependency>

3.2 coding

1. Write a Hello entity class

package com.kuang.pojo;public class Hello {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public void show(){        System.out.println("Hello,"+name);    }}

2. Write our spring file, which is named beans 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 "> <! -- beans are java objects created and managed by spring -- > < bean id =" hello "class =" com kuang. pojo. Hello">        <property name="name" value="Spring"/>    </bean></beans>

3. Test

public void test(){    //Parse beans XML file to generate and manage the corresponding bean object ApplicationContext context = new classpathxmlapplicationcontext ("beans.xml")// GetBean: the parameter is the ID of the bean in the Spring configuration file. Hello hello = (Hello) context getBean("hello");     hello. show();}

3.3 thinking

  • Who created the Hello object?

    The hello object is created by Spring

  • How are the properties of the Hello object set?

    The properties of the hello object are set by the Spring container. This process is called control inversion

  • Control: who controls the creation of objects? Traditional applications are created by the program itself. After using Spring, objects are created by Spring

  • Inversion: the program itself does not create an object, but becomes a passive receiving object.

Dependency injection: it uses the set method to inject.

IOC is a programming idea, which changes from active programming to passive reception

You can browse the underlying source code through the new ClassPathXmlApplicationContext.

3.4 modification case I

In case 1, Xing adds a Spring configuration file beans 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 "> <! -- beans are java objects created and managed by Spring -- > < bean id =" mysqlimpl "class =" com kuang. dao. UserDaoMysqlImpl">    </bean>    <bean id="OracleImpl" class="com. kuang. dao. UserDaoOracleImpl">    </bean>    <bean id="ServiceImpl" class="com. kuang. service. Userserviceimpl "> <! -- Note: the name here is not a property, but the part behind the set method. The initial is lowercase -- > <! -- it refers to another bean, not value, but ref; the basic type uses value -- > < property name =" userdao "ref =" mysqlimpl "/ > < / bean > < / beans >

Retest:

@Testpublic void getUser() {    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");    UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("ServiceImpl");    serviceImpl.getUser();}
  • OK, now, we don't need to change it in the program at all. To realize different operations, we only need to modify it in the xml configuration file.
  • The so-called IOC is done in one sentence: objects are created, managed and assembled by Spring.

3.5 my understanding

  1. At the beginning, an interface of dao layer has multiple implementation classes. The service layer references the interface and implements one of the implementation classes. If users (test s) want to change and access different dao layer implementation classes, they need to modify the service layer's reference to dao layer implementation classes, so they need to modify the program. The initiative is in the hands of the program. When this demand is large, the program modification is very cumbersome.

    public class UserDaoOracleImpl implements UserService {    //Associate dao layer objects in the service layer and modify the new object private userdao userdao = new userdaooracleimpl()@ Override    public void getUser() {        userDao.getUser();    }}
    
  2. The first modification: we refer to the dao layer implementation class from the service layer. Instead of implementing it, we change the interface into an attribute and reserve the attribute set interface. When the user (test) wants to use which dao layer to implement the class, he only needs to pass in the corresponding dao layer implementation class object when the test layer calls serviceImpl, and the initiative is in the user's hand.

    public class UserServiceImpl implements UserService {    //Associate the dao layer object private UserDao userDao in the service layer// [revolutionary change] the dao layer interface implementation class used in the service layer often changes, so instead of implementing it, an interface public void setuserdao (userdao userdao) {this. Userdao = userdao;}@ Override    public void getUser() {        userDao.getUser();    }}
    
    @Testpublic void getUser(){    UserServiceImpl userService = new UserServiceImpl();    //Mysql implements userservice setUserDao(new UserDaoMysqlImpl());     userService. getUser();    // Oracle implements userservice setUserDao(new UserDaoOracleImpl());     userService. getUser();}
    
  3. Using Spring:

    • Every class in the project goes to beans Register in XML
    • The properties of each class are also set (injected) during registration, including basic type properties and reference type properties (referring to other objects)
    • When the project is built, the Spring framework will build all the class objects, and only one copy of all the objects in the whole Spring will be reserved
    • When using (test), use new ClassPathXmlApplicationContext("beans.xml"); Get all the objects created and managed by Spring
    • To modify the reference to dao layer objects in the service layer, you can directly modify beans XML configuration file without modifying the program.
    • Control: all objects are created and managed by Spring
    • Inversion: through beans XML can configure the attributes of each object and other objects it refers to. The user has the choice and initiative (assuming that the user can operate beans.xml indirectly)
<?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 "> <! -- beans are java objects created and managed by Spring -- > < bean id =" mysqlimpl "class =" com kuang. dao. UserDaoMysqlImpl">    </bean>    <bean id="OracleImpl" class="com. kuang. dao. UserDaoOracleImpl">    </bean>    <bean id="ServiceImpl" class="com. kuang. service. Userserviceimpl "> <! -- Note: the name here is not a property, but the part behind the set method. The initial is lowercase -- > <! -- it refers to another bean, not value, but ref; the basic type uses value -- > < property name =" userdao "ref =" mysqlimpl "/ > < / bean > < / beans >

test does not need to be modified, just modify the above beans XML configuration file

@Testpublic void getUser() {    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");   UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("ServiceImpl");   serviceImpl.getUser();}

4.IOC object creation method

4.1 create by parameterless construction method

1. Entity class User

public class User {    private String name;    public User(){        System.out.println("user Nonparametric construction method");    }    public void setName(String name){        this.name=name;    }    public void show(){        System.out.println("name="+name);    }}

2.Spring configuration file beans 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 "> <! -- beans are java objects created and managed by Spring -- > < bean id =" user "class =" com kuang. pojo. User">        <property name="name" value="kuangshen"/>    </bean></beans>

3. Breakpoint test

Test results:

  • When the test class passes ApplicationContext, context = new classpathxmlapplicationcontext ("beans.xml"); The configuration file beans When XML is loaded into Spring for execution, the context of Spring is obtained.

    At this time, all managed objects have been initialized, and the User object has been initialized through parameterless construction.

  • In this operation, Spring has created and managed all the beans Register the configured object in XML.

  • Object properties are configured through the set method corresponding to the property.

    After deleting the setName method in User, beans An error will be reported for the parameters of the XML configuration class.

4.2 create by parametric construction method

1. Entity class User

public class User {
    private String name;

    //Parametric construction method
    public User(String name){
        this.name=name;
        System.out.println("user Parametric construction method");
    }

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

    public void show(){
        System.out.println("name="+name);
    }
}

2.beans. Three ways to write XML

  • At this time, the entity class User cannot be initialized through < property name = "name" value = "kuangshen" / > because it can only be created when it is a parameterless construction method
  • The parameter construction method adopts < constructor Arg name = "name" value = "kuangshen" / > to configure attributes

Set common according to the parameter name, and the latter two are not common

<!-- The first is to set [common] according to the parameter name -->
<bean id="user" class="com.kuang.pojo.User">
    <constructor-arg name="name" value="kuangshen"/>
</bean>
<!-- Second basis index Parameter subscript setting -->
<bean id="userT" class="com.kuang.pojo.UserT">
    <!-- index Refers to the construction method , Subscript starts at 0 -->
    <constructor-arg index="0" value="kuangshen2"/>
</bean>
<!-- The third is set according to the parameter type -->
<bean id="userT" class="com.kuang.pojo.UserT">
<constructor-arg type="java.lang.String" value="kuangshen2"/>
</bean>

3. Test

  • Similarly, once the Spring context is obtained, that is, when the configuration file is loaded, all entity classes are initialized

  • Whether it is through parameterless construction, it depends on set method injection

  • Or through the parametric structure. At this time, it is injected directly through the parametric structure

  • Some attributes can be constructed through parameters, and some attributes can be injected through set

    <bean id="user" class="com.kuang.pojo.User">
        <!--name Properties are constructed with parameters, without set method-->
        <constructor-arg name="name" value="kuangshen"/> 
        <!--age Property is not initialized in a parameterized construct, set Method must have-->
        <property name="age" value="12"/>
    </bean>
    

5.Spring configuration

5.1 alias

Alias sets an alias for a bean. You can set multiple aliases

<bean id="user" class="com.kuang.pojo.User">
    <property name="name" value="kuangshen"/>
</bean>

<!--by bean Set alias: get when testing Bean You can use alias to get-->
<alias name="user" alias="usernew"/>

5.2 bean configuration

<!--bean namely java object,from Spring Container creation and management
	id: yes bean Unique identifier of, if not configured id,name Is the default flag
	class: bean The fully qualified name corresponding to the object=Package name+Class name
	name: Can be bean Set multiple aliases, which can be separated by commas, semicolons and spaces
-->
<bean id="user" class="com.kuang.pojo.User" name="u1,u2 u3;u4">
    <property name="name" value="kuangshen"/>
</bean>

5.3import

  • Import is generally used for team development. You can import other configuration files in one configuration file and merge them into one
  • beans. The formal name of XML is ApplicationContext xml
  • If there are multiple developers in the project, different people are responsible for the development of different classes, and different classes need to be registered in different beans In XML, we can import everyone's beans The XML is merged into a total.
  • When using, just use the general configuration directly

For example: beans1 xml,beans2.xml,beans3. xml ==> applicationContext. xml

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

    <!--Overall xml,Merge other beans.xml file-->
    <import resource="beans1.xml"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>

</beans>

Test:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

6. Dependency injection (key)

  • **Dependency: * * the creation of bean objects depends on the container
  • Injection: all attributes in the bean object are injected by the container. In short, it is to assign values to the attributes in the object

6.1 constructor injection (mentioned earlier)

Parameterless construction method injection = = "is injected using the set method

Parametric construction method injection

6.2Set injection method

The class injected by the set method must have a parameterless constructor

Test object:

Address class:

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Address{" +
                "address='" + address + '\'' +
                '}';
    }
}

Student class:

public class Student {
    private String name;
    private Address address;

    private String[] books;
    private List<String> hobbies;
    private Map<String,String> card;
    private Set<String> games;

    private String wife;
    private Properties info;


    //Nonparametric structure
    public Student() {
    }

    //Parametric structure
    public Student(String name, Address address, String[] books, List<String> hobbies, Map<String, String> card, Set<String> games, String wife, Properties info) {
        this.name = name;
        this.address = address;
        this.books = books;
        this.hobbies = hobbies;
        this.card = card;
        this.games = games;
        this.wife = wife;
        this.info = info;
    }

    //getter and setter

    public String getName() {
        return name;
    }

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

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    public Properties getInfo() {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    //toString

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", hobbies=" + hobbies +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}

beans. Class registration and attribute injection in XML

Injection attribute classification: common injection value, bean injection ref, array, list, map, set, null and properties

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

    <!--register Address class-->
    <bean id="address" class="com.kuang.pojo.Address">
        <property name="address" value="Beijing"/>
    </bean>

    <!--register Student class-->
    <bean id="student" class="com.kuang.pojo.Student">
        <!--1 Normal injection, value-->
        <property name="name" value="Xiao Ming"/>
        <!--2 bean Injection, ref-->
        <property name="address" ref="address"/>

        <!--3 Array, array-->
        <property name="books">
            <array>
                <value>The Dream of Red Mansion</value>
                <value>Journey to the West</value>
                <value>Romance of the Three Kingdoms</value>
                <value>Water Margin</value>
            </array>
        </property>
        <!--4 List,list-->
        <property name="hobbies">
            <list>
                <value>listen to the music</value>
                <value>Knock code</value>
                <value>Look, little sister</value>
                <value>watch movie</value>
            </list>
        </property>
        <!--5 Map,map-->
        <property name="card">
            <map>
                <entry key="ID" value="12345678"/>
                <entry key="bank card" value="87654321"/>
            </map>
        </property>
        <!--6 Set,set-->
        <property name="games">
            <set>
                <value>Mario</value>
                <value>Contra</value>
                <value>Tank Battle</value>
            </set>
        </property>

        <!--7 null Different from empty string-->
        <property name="wife">
            <null/>
        </property>
        <!--8 properties-->
        <property name="info">
            <props>
                <prop key="driver">20210710</prop>
                <prop key="url">man</prop>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>

    </bean>

</beans>

Test:

public void test(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

   Student student = (Student) context.getBean("student");
    System.out.println(student.toString());
}

Test results:

Student{
    name='Xiao Ming', 
    address=Address{address='Beijing'},
    books=[The Dream of Red Mansion, Journey to the West, Romance of the Three Kingdoms, Water Margin], 
    hobbies=[listen to the music, Knock code, Look, little sister, watch movie], 
    card={
        ID=12345678, 
        bank card=87654321
    }, 
    games=[Mario, Contra, Tank Battle], 
    wife='null',
    info={
        password=123456,
        url=man, 
        driver=20210710, 
        username=root
    }
}

6.3 expansion mode injection (p namespace injection, c namespace injection)

Essence:

  • p namespace injection or parameter free construction method injection (parameter free construction method is required in entity class)
  • c namespace injection is injection using parameterized construction methods (parameterized construction methods are required in entity classes)

1.P namespace injection: a constraint file needs to be added to the header file

Import constraints : xmlns:p="http://www.springframework.org/schema/p"

<!--P(Properties: properties)Namespace, attributes are still parameterless in nature, and methods are constructed through set injection-->
<bean id="student" class="com.kuang.pojo.Student" p:name="Xiao Ming"/>

2.c namespace injection: a constraint file needs to be added to the header file

Import constraints : xmlns:c="http://www.springframework.org/schema/c"

<!--C(Construction: Constructor)Namespace and attribute are still parameter construction method injection in essence, which can be omitted set method-->
<bean id="student" class="com.kuang.pojo.Student" p:name="Xiao Ming"/>

Attribute injection summary

  • In essence, it is also attribute injection of nonparametric construction method and parameter construction method injection
    • **Parameterless construction method injection: * * that is, it is injected through the set method. Therefore, when injecting through the set method, there must be parameterless construction methods in the class, but they exist by default
    • **Parameter constructor injection: * * it is injected directly through the attribute assignment of the parameter constructor, so the parameter constructor must be rewritten; Note that at this time, don't forget to explicitly add a parameterless constructor to adapt to set method injection
  • In essence, p namespace and c namespace injection still use parameterless construction method and parameterless construction method

6.4 scope of bean

The object created by bean for each class has six scopes:

1. Singleton mode (Spring default mechanism: each time you get a bean from the container, you get the same object)

beans.xml:

<bean id="user" class="com.kuang.pojo.User" scope="singleton">

test:

public void test(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    User user1 = (User) context.getBean("user");
    User user2 = (User) context.getBean("user");
    System.out.println(user1==user2);  //true

}

2. Prototype pattern (each time you get a bean from the container, a new object will be generated)

beans.xml:

<bean id="user" class="com.kuang.pojo.User" scope="prototype">

test:

System.out.println(user1==user2);  //false

3. Other request s, session s and application s can only be used in web development!

Keywords: Spring

Added by quadlo on Thu, 20 Jan 2022 15:59:57 +0200