Spring—— Spring IOC 2

Keywords: Spring xml encoding JDBC

Articles Catalogue

1. Beans in Spring are generated according to scope, representing the scope of bean s.

There are four types of scope:

  1. singleton: singleton, which indicates that the object obtained through the Spring container is unique.
  2. prototype: prototype, which means that objects acquired through Spring containers are different.
  3. reqeust: Request that is valid within an http request.
  4. Session: Session, which means valid within a user session.

3 and 4 are only applicable to web projects. In most cases, we only use singleton and prototype scopes, and the default value of scope is singleton.

We will learn the difference between the two configurations through an example.

1. Create User entity classes.

/**
 * @ClassName User
 * @Description
 * @Author lzq
 * @Date 2019/8/9 14:30
 * @Version 1.0
 **/
public class User {
    private int id;
    private String name;
    private int age;

    public User() {
        System.out.println("Created User object");
    }
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }

   @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2. Configure the instantiated bean of User in spring.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">

     <bean id="user" class="com.study.bean.User">
        <property name="id" value="1"></property>
        <property name="name" value="Zhang San"></property>
        <property name="age" value="23"></property>
    </bean>

</beans>

3. The test class obtains two User instantiated objects user1 and user2 through the Spring container, and determines whether they are the same object by the == method.

public class TestDemo1 {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        User user = (User) applicationContext.getBean("user");
        User user2 = (User) applicationContext.getBean("user");
        System.out.println(user == user2);
    }
}


The result is printed true, and the User constructor is executed only once, indicating that user1 and user2 are the same objects, so scope defaults to singleton, meaning that objects created by default through the Spring container are singleton patterns.

Modify the configuration in spring.xml to change scope to prototype.

<?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="user" class="com.study.bean.User" scope="prototype">
        <property name="id" value="1"></property>
        <property name="name" value="Zhang San"></property>
        <property name="age" value="23"></property>
    </bean>

</beans>

Execute code:

As you can see, the constructor is called twice, and the result of == is false, indicating that user1 and user2 are now two objects.

2.Spring's inheritance,

Unlike Java inheritance, the idea is very similar. A child bean can inherit attributes from a parent bean.

Seeing this, someone will ask if a child bean can inherit the method in the parent bean.

In fact, there is no inheritance of methods. Spring's inheritance operates at the object level, that is, two bean s come from the same class, so the method is the same, and there is no inheritance relationship.

1. Configure two User bean s in spring. XML and establish inheritance relationships.

<?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="user" class="com.study.bean.User">
        <property name="id" value="1"></property>
        <property name="name" value="Zhang San"></property>
        <property name="age" value="23"></property>
    </bean>

    <bean id="user2" class="com.study.bean.User" parent="user"></bean>

</beans>

Execute code:

public class TestDemo1 {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        User user = (User) applicationContext.getBean("user2");
        System.out.println(user);
    }
}


As you can see, two User objects user1 and user2 are created, and user2 inherits all properties of user1.

On the basis of inheriting all the attributes of user1, user2 can also override the attributes by adding property directly to spring.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">

     <bean id="user" class="com.study.bean.User">
        <property name="id" value="1"></property>
        <property name="name" value="Zhang San"></property>
        <property name="age" value="23"></property>
    </bean>

    <bean id="user2" class="com.study.bean.User" parent="user">
        <!-- cover name attribute -->
        <property name="name" value="Li Si"></property>
    </bean>

</beans>

Running code:

The name attribute has been modified to Lisi to complete the coverage.

So can bean s in Spring inherit from one class to another?

The answer is yes, but the attribute list of these two classes needs to be identical, otherwise it will be wrong, which will not be used in actual development.

3.Spring's dependence.

Similar to inheritance, dependency is also a way of association between beans. After configuring dependencies, the dependent beans must be created first and then the dependent beans.

We still understand it through code.

1. Create Car entity classes.

/**
 * @ClassName Car
 * @Description
 * @Author lzq
 * @Date 2019/8/9 14:55
 * @Version 1.0
 **/
public class Car {
    private int id;
    private String brand;

    public Car() {
        System.out.println("Created Car object");
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Car{" +
                "id=" + id +
                ", brand='" + brand + '\'' +
                '}';
    }
}

2. Configure User bean, Car bean in spring.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">

     <bean id="user" class="com.study.bean.User">
        <property name="id" value="1"></property>
        <property name="name" value="Zhang San"></property>
        <property name="age" value="23"></property>
    </bean>

    <bean id="car" class="com.study.bean.Car">
        <property name="id" value="1"></property>
        <property name="brand" value="BMW"></property>
    </bean>
</beans>

Running code:

/**
 * @ClassName TestDemo1
 * @Description
 * @Author lzq
 * @Date 2019/8/9 12:21
 * @Version 1.0
 **/
public class TestDemo1 {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        User user = (User) applicationContext.getBean("user");
        Car car = (Car) applicationContext.getBean("car");
    }
}

Operation results:

When you see the result, you create User first and Car later, which is determined by the order of beans in spring.xml. First come first serve, first configure User bean s, so you create User objects first.

Now modify the spring.xml configuration, and the User relies on Car to set dependent-on 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 http://www.springframework.org/schema/beans/spring-beans.xsd">

     <bean id="user" class="com.study.bean.User" depends-on="car">
        <property name="id" value="1"></property>
        <property name="name" value="Zhang San"></property>
        <property name="age" value="23"></property>
    </bean>

    <bean id="car" class="com.study.bean.Car">
        <property name="id" value="1"></property>
        <property name="brand" value="BMW"></property>
    </bean>
</beans>

Run the code again, see the result, create Car first, then User, because User depends on Car, so Car object must be created first, User object can complete the dependency.

4.Spring reads external resources.

In general development, the configuration of database will be saved in a properties file for easy maintenance. If Spring container is used to generate data source objects, how to read the contents of the properties configuration file?

1. Create jdbc.properties.

driverName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8
user = root
pwd = 123456

2. In this place, we use the new spring-plus.xml to configure the C3P0 data source.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- Import external resource files -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!-- Establish C3P0 data source -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${user}"></property>
        <property name="password" value="${pwd}"></property>
        <property name="driverClass" value="${driverName}"></property>
        <property name="jdbcUrl" value="${url}"></property>
    </bean>

</beans>

Step 1: Import external resource files. Using the context:property-placeholder tag, you need to import the context namespace.

Step 2: Get the value of the external resource file through the ${} expression.

3. Test code:

/**
 * @ClassName TestDemo2
 * @Description
 * @Author lzq
 * @Date 2019/8/9 15:15
 * @Version 1.0
 **/
public class TestDemo2 {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-plus.xml");
        DataSource ds = (DataSource) applicationContext.getBean("dataSource");
        Connection conn = null;
        try {
            conn = ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(conn);
    }
}

4. Run the code, see the results, print the dataSource object.

In addition to assembling values and references for bean attributes using elements, Spring also provides another way of assembling bean attributes: p namespaces, which further simplifies configuration code.

Posted by Johns3n on Fri, 09 Aug 2019 00:42:33 -0700