spring framework -- basic use of IOC

Keywords: Spring Framework

Through the previous introduction, we have learned that a very important feature of spring is IOC. Next, we will take a look at how to use IOC container to help you better understand the advantages of spring.

1,spring_helloworld

(1) It is implemented by manually loading the jar package, which is divided into three steps. Now it is almost unnecessary

  • Guide Package: import these five packages

    commons-logging-1.2.jar spring-beans-5.2.3.RELEASE.jar spring-context-5.2.3.RELEASE.jar spring-core-5.2.3.RELEASE.jar spring-expression-5.2.3.RELEASE.jar

  • Write configuration

    Person.java

    package com.mashibing.bean;
    
    public class Person {
        private int id;
        private String name;
        private int age;
        private String gender;
    
        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;
        }
    
        public String getGender() {
            return gender;
        }
    
        public void setGender(String gender) {
            this.gender = gender;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    ", gender='" + gender + '\'' +
                    '}';
        }
    }
    
    

    ioc.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">
    
        <!--Register an object, spring Back to automatically create this object-->
        <!--
        One bean The label represents an object
        id:The unique identifier of this object
        class:The fully qualified name of the registered object
        -->
        <bean id="person" class="com.mashibing.bean.Person">
            <!--use property The tag assigns values to the properties of the object
            name:Represents the name of the property
            value: Represents the value of the property
            -->
            <property name="id" value="1"></property>
            <property name="name" value="zhangsan"></property>
            <property name="age" value="18"></property>
            <property name="gender" value="male"></property>
        </bean>
    </beans>
    
  • test

SpringDemoTest.java

package com.mashibing.test;

import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDemoTest {
    public static void main(String[] args) {
        //ApplicationContext: represents the ioc container
        //ClassPathXmlApplicationContext: indicates the configuration of obtaining xml files from the current classpath path
        //Get the ioc container object according to the spring configuration file
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        Person person = (Person) context.getBean("person");
        System.out.println(person);
    }
}

(2) Use maven to build the project

  • Create maven project

    Define the groupId and artifactId of the project

  • Add the corresponding pom dependency

    pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.mashibing</groupId>
        <artifactId>spring_demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.2.3.RELEASE</version>
            </dependency>
        </dependencies>
    </project>
    
  • Write code

    Person.java

    package com.mashibing.bean;
    public class Person {
        private int id;
        private String name;
        private int age;
        private String gender;
    
        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;
        }
    
        public String getGender() {
            return gender;
        }
    
        public void setGender(String gender) {
            this.gender = gender;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    ", gender='" + gender + '\'' +
                    '}';
        }
    }
    
  • test

    MyTest.java

import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        Person person = (Person) context.getBean("person");
        System.out.println(person);
    }
}

Summary:

Both of the above two methods can be used to create spring projects, but maven is more used in the current enterprise development environment. There is no need to deal with the dependencies between jars and download jar packages in advance. You only need to configure relevant POMs. Therefore, maven is recommended, For specific maven operations, you can see the detailed operation documents of maven.

Points to note in setting up spring projects:

1. Be sure to add the configuration file to the classpath. When creating a project with idea, it should be placed in the resource directory

2. Don't forget the commons-logging-1.2.jar package when guiding the package

Fine node:

1. ApplicationContext is the interface of IOC container. You can obtain the objects created in the container through this object

2. The object is created when the Spring container is created, not when it needs to be used

3. When objects are stored in the IOC container, they are single instances. If multiple instances are needed, the attributes need to be modified

4. When creating an object to assign a value to a property, it is implemented through the setter method

5. The attribute of the object is determined by the setter/getter method, not the defined member attribute

2. spring object acquisition and attribute assignment method

1. Get the object in the IOC container through the id of the bean (used above)

2. Get the object by the type of the bean

​ MyTest.java

import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        Person bean = context.getBean(Person.class);
        System.out.println(bean);
    }
}

Note: when searching for objects through bean types, two bean objects with the same type cannot exist in the configuration file. If any, you can use the following methods

MyTest.java

import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
        Person person = context.getBean("person", Person.class);
        System.out.println(person);
    }
}

3. Assign a value to the bean object through the constructor

ioc.xml

	<!--to person Class add constructor-->
	<bean id="person2" class="com.mashibing.bean.Person">
        <constructor-arg name="id" value="1"></constructor-arg>
        <constructor-arg name="name" value="lisi"></constructor-arg>
        <constructor-arg name="age" value="20"></constructor-arg>
        <constructor-arg name="gender" value="female"></constructor-arg>
    </bean>

	<!--It can be omitted when using constructor assignment name Property, but at this time, it is required to fill in strictly in the order of constructor parameters-->
	<bean id="person3" class="com.mashibing.bean.Person">
        <constructor-arg value="1"></constructor-arg>
        <constructor-arg value="lisi"></constructor-arg>
        <constructor-arg value="20"></constructor-arg>
        <constructor-arg value="female"></constructor-arg>
    </bean>

	<!--If you want to add parameter values out of order, you can match them index Property to use-->
    <bean id="person4" class="com.mashibing.bean.Person">
        <constructor-arg value="lisi" index="1"></constructor-arg>
        <constructor-arg value="1" index="0"></constructor-arg>
        <constructor-arg value="female" index="3"></constructor-arg>
        <constructor-arg value="20" index="2"></constructor-arg>
    </bean>
	<!--When there are multiple constructors of different types with the same number of parameters, you can type To force the type-->
	take person of age Type set to Integer type
	public Person(int id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
        System.out.println("Age");
    }

    public Person(int id, String name, String gender) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        System.out.println("gender");
    }
	<bean id="person5" class="com.mashibing.bean.Person">
        <constructor-arg value="1"></constructor-arg>
        <constructor-arg value="lisi"></constructor-arg>
        <constructor-arg value="20" type="java.lang.Integer"></constructor-arg>
    </bean>
	<!--If not, change to integer Type, then you need type Follow index Combined use-->
	 <bean id="person5" class="com.mashibing.bean.Person">
        <constructor-arg value="1"></constructor-arg>
        <constructor-arg value="lisi"></constructor-arg>
        <constructor-arg value="20" type="int" index="2"></constructor-arg>
    </bean>

4. Assigning values to bean s through namespaces simplifies the writing of attribute declarations in configuration files

1. Import namespace

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

2. Add configuration

    <bean id="person6" class="com.mashibing.bean.Person" p:id="3" p:name="wangwu" p:age="22" p:gender="male"></bean>

5. Assign values to complex types

In the previous test code, we assign values to the most basic attributes. In normal enterprise development, we will also encounter assigning values to various complex types, such as sets, arrays, other objects, etc.

​ Person.java

package com.mashibing.bean;

import java.util.*;

public class Person {
    private int id;
    private String name="dahuang";
    private int age;
    private String gender;
    private Address address;
    private String[] hobbies;
    private List<Book> books;
    private Set<Integer> sets;
    private Map<String,Object> maps;
    private Properties properties;

    public Person(int id, String name, int age, String gender) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        System.out.println("Parametric constructor");
    }

    public Person(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
        System.out.println("Age");
    }

    public Person(int id, String name, String gender) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        System.out.println("gender");
    }

    public Person() {
    }

    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;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Address getAddress() {
        return address;
    }

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

    public List<Book> getBooks() {
        return books;
    }

    public void setBooks(List<Book> books) {
        this.books = books;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public String[] getHobbies() {
        return hobbies;
    }

    public void setHobbies(String[] hobbies) {
        this.hobbies = hobbies;
    }

    public Set<Integer> getSets() {
        return sets;
    }

    public void setSets(Set<Integer> sets) {
        this.sets = sets;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", address=" + address +
                ", hobbies=" + Arrays.toString(hobbies) +
                ", books=" + books +
                ", sets=" + sets +
                ", maps=" + maps +
                ", properties=" + properties +
                '}';
    }
}


Book.java

package com.mashibing.bean;

public class Book {
    private String name;
    private String author;
    private double price;

    public Book() {
    }

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}

Address.java

package com.mashibing.bean;

public class Address {
    private String province;
    private String city;
    private String town;

    public Address() {
    }

    public Address(String province, String city, String town) {
        this.province = province;
        this.city = city;
        this.town = town;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getTown() {
        return town;
    }

    public void setTown(String town) {
        this.town = town;
    }

    @Override
    public String toString() {
        return "Address{" +
                "province='" + province + '\'' +
                ", city='" + city + '\'' +
                ", town='" + town + '\'' +
                '}';
    }
}

ioc.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"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd"
>

    <!--Assignments to complex types are property In label-->
    <bean id="person" class="com.mashibing.bean.Person">
        <property name="name">
            <!--Null value-->
            <null></null>
        </property>
        <!--adopt ref Reference other objects, reference external bean-->
        <property name="address" ref="address"></property>
        <!--Reference internal bean-->
       <!-- <property name="address">
            <bean class="com.mashibing.bean.Address">
                <property name="province" value="Beijing"></property>
                <property name="city" value="Beijing"></property>
                <property name="town" value="Xicheng District"></property>
            </bean>
        </property>-->
        <!--by list assignment-->
        <property name="books">
            <list>
                <!--inside bean-->
                <bean id="book1" class="com.mashibing.bean.Book">
                    <property name="name" value="Multithreading and high concurrency"></property>
                    <property name="author" value="hibernate "></property>
                    <property name="price" value="1000"></property>
                </bean>
                <!--external bean-->
                <ref bean="book2"></ref>
            </list>
        </property>
        <!--to map assignment-->
        <property name="maps" ref="myMap"></property>
        <!--to property assignment-->
        <property name="properties">
            <props>
                <prop key="aaa">aaa</prop>
                <prop key="bbb">222</prop>
            </props>
        </property>
        <!--Assign a value to an array-->
        <property name="hobbies">
            <array>
                <value>book</value>
                <value>movie</value>
                <value>game</value>
            </array>
        </property>
        <!--to set assignment-->
        <property name="sets">
            <set>
                <value>111</value>
                <value>222</value>
                <value>222</value>
            </set>
        </property>
    </bean>
    <bean id="address" class="com.mashibing.bean.Address">
        <property name="province" value="Hebei"></property>
        <property name="city" value="Handan"></property>
        <property name="town" value="Wu'an"></property>
    </bean>
    <bean id="book2" class="com.mashibing.bean.Book">
        <property name="name" value="JVM"></property>
        <property name="author" value="hibernate "></property>
        <property name="price" value="1200"></property>
    </bean>
    <!--Cascade attribute-->
    <bean id="person2" class="com.mashibing.bean.Person">
        <property name="address" ref="address"></property>
        <property name="address.province" value="Beijing"></property>
    </bean>
    <!--util Namespace to create a collection type bean-->
    <util:map id="myMap">
            <entry key="key1" value="value1"></entry>
            <entry key="key2" value-ref="book2"></entry>
            <entry key="key03">
                <bean class="com.mashibing.bean.Book">
                    <property name="name" value="Journey to the West" ></property>
                    <property name="author" value="Wu Chengen" ></property>
                    <property name="price" value="100" ></property>
                </bean>
            </entry>
    </util:map>
</beans>

6. Configuration of inheritance bean

ioc.xml

    <bean id="person" class="com.mashibing.bean.Person">
        <property name="id" value="1"></property>
        <property name="name" value="zhangsan"></property>
        <property name="age" value="21"></property>
        <property name="gender" value="male"></property>
    </bean>
    <!--parent:appoint bean Which configuration information is inherited from bean-->
    <bean id="person2" class="com.mashibing.bean.Person" parent="person">
        <property name="name" value="lisi"></property>
    </bean>

If you want to implement the abstract class of Java files and do not need to instantiate the current bean, you can use the abstract attribute

 	<bean id="person" class="com.mashibing.bean.Person" abstract="true">
        <property name="id" value="1"></property>
        <property name="name" value="zhangsan"></property>
        <property name="age" value="21"></property>
        <property name="gender" value="male"></property>
    </bean>
    <!--parent:appoint bean Which configuration information is inherited from bean-->
    <bean id="person2" class="com.mashibing.bean.Person" parent="person">
        <property name="name" value="lisi"></property>
    </bean>

7. Dependencies created by bean objects

bean objects are created according to the order of beans in the configuration file. You can also use the dependent on tag to determine the order

ioc.xml

	<bean id="book" class="com.mashibing.bean.Book" depends-on="person,address"></bean>
    <bean id="address" class="com.mashibing.bean.Address"></bean>
    <bean id="person" class="com.mashibing.bean.Person"></bean>

8. The scope of the bean controls whether it is a singleton

ioc.xml

    <!--
    bean Scope of: singleton,prototype,request,session
    Singleton by default
    prototype: Multi instance
        Multiple instances will not be created when the container starts bean,The object is created only when it is acquired
        Each creation is a new object
    singleton: Default singleton
        The object is created before the container is started
        All objects obtained are the same
    -->
    <bean id="person4" class="com.mashibing.bean.Person" scope="prototype"></bean>

9. Create bean objects using factory pattern

In the previous case, all bean objects were created through reflection to get the corresponding bean instances. In fact, spring also includes another way to create bean instances, that is, to create objects through factory mode

There are two ways to create bean instances using factory pattern: static factory and instance factory.

Static factory: the factory itself does not need to create objects, but can be called through static methods. Object = factory class. Static factory method name ();

Instance factory: the factory itself needs to create an object. Factory class factory object = new factory class; Factory object. get object name ();

PersonStaticFactory.java

package com.mashibing.factory;

import com.mashibing.bean.Person;

public class PersonStaticFactory {

    public static Person getPerson(String name){
        Person person = new Person();
        person.setId(1);
        person.setName(name);
        return person;
    }
}

ioc.xml

<!--
Use of static plants:
class:Specify static factory class
factory-method:Specifies which method is a factory method
-->
<bean id="person5" class="com.mashibing.factory.PersonStaticFactory" factory-method="getPerson">
        <!--constructor-arg: You can specify parameters for the method-->
        <constructor-arg value="lisi"></constructor-arg>
    </bean>

PersonInstanceFactory.java

package com.mashibing.factory;

import com.mashibing.bean.Person;

public class PersonInstanceFactory {
    public Person getPerson(String name){
        Person person = new Person();
        person.setId(1);
        person.setName(name);
        return person;
    }
}

ioc.xml

    <!--Instance factory usage-->
    <!--Create instance factory class-->
    <bean id="personInstanceFactory" class="com.mashibing.factory.PersonInstanceFactory"></bean>
    <!--
    factory-bean:Specify which factory instance to use
    factory-method:Specifies the method of which factory instance to use
    -->
    <bean id="person6" class="com.mashibing.bean.Person" factory-bean="personInstanceFactory" factory-method="getPerson">
        <constructor-arg value="wangwu"></constructor-arg>
    </bean>

10. Inherit FactoryBean to create objects

FactoryBean is an interface specified by spring. Spring will regard the implementation class of the current interface as a factory. However, an instance will not be created when the ioc container is started, and an object will be created only when it is used

MyFactoryBean.java

package com.mashibing.factory;

import com.mashibing.bean.Person;
import org.springframework.beans.factory.FactoryBean;

/**
 * The class that implements the FactoryBean interface is a recognized factory class in spring. Spring will automatically call the factory method to create an instance
 */
public class MyFactoryBean implements FactoryBean<Person> {

    /**
     * Factory method to return the object to be created
     * @return
     * @throws Exception
     */
    @Override
    public Person getObject() throws Exception {
        Person person = new Person();
        person.setName("maliu");
        return person;
    }

    /**
     * Return the type of the created object. spring will automatically call this method to return the type of the object
     * @return
     */
    @Override
    public Class<?> getObjectType() {
        return Person.class;
    }

    /**
     * Is the created object a singleton
     * @return
     */
    @Override
    public boolean isSingleton() {
        return false;
    }
}

ioc.xml

<bean id="myfactorybean" class="com.mashibing.factory.MyFactoryBean"></bean>

11. Initialization and destruction methods of bean objects

When creating objects, we can call initialization and destruction methods as needed

Address.java

package com.mashibing.bean;

public class Address {
    private String province;
    private String city;
    private String town;

    public Address() {
        System.out.println("address Was created");
    }

    public Address(String province, String city, String town) {
        this.province = province;
        this.city = city;
        this.town = town;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getTown() {
        return town;
    }

    public void setTown(String town) {
        this.town = town;
    }

    public void init(){
        System.out.println("Object is initialized");
    }
    
    public void destory(){
        System.out.println("Object destroyed");
    }
    
    @Override
    public String toString() {
        return "Address{" +
                "province='" + province + '\'' +
                ", city='" + city + '\'' +
                ", town='" + town + '\'' +
                '}';
    }
}

ioc.xml

<!--bean Lifecycle representation bean Create to destroy
        If bean This is a single example. The container will be created when it is started and destroyed when it is closed bean
        If bean It's polite. You create objects when you get them, and there will be no calls when you destroy them
    -->
    <bean id="address" class="com.mashibing.bean.Address" init-method="init" destroy-method="destory"></bean>

MyTest.java

import com.mashibing.bean.Address;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc2.xml");
        Address address = context.getBean("address", Address.class);
        System.out.println(address);
        //applicationContext has no close method and needs to use specific subclasses
        ((ClassPathXmlApplicationContext)context).close();

    }
}

12. Configure the pre-processing and post-processing methods of the bean object initialization method

spring contains a BeanPostProcessor interface, which can be called back and forth before and after the initialization method of bean. If the initialization method and the post processor are configured, whether or not initialization methods are included, it will be called.

MyBeanPostProcessor.java

package com.mashibing.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {
    /**
     * Execute before initializing method calls
     * @param bean  Initialized bean object
     * @param beanName  xml The id attribute of the bean in the configuration file
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization:"+beanName+"Call the initialization pre method");
        return bean;
    }

    /**
     * Execute after initializing method calls
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization:"+beanName+"Call the initialization suffix method");
        return bean;
    }
}

ioc.xml

<bean id="myBeanPostProcessor" class="com.mashibing.bean.MyBeanPostProcessor"></bean>

3. spring creates third-party bean objects

In spring, many objects are single instance. In daily development, we often need to use some external single instance objects, such as database connection pool. Let's explain how to create a third-party bean instance in spring.

1. Import the pom file of the database connection pool

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

2. Write configuration file

ioc.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="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/demo"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    </bean>
</beans>

3. Prepare test documents

MyTest.java

import com.alibaba.druid.pool.DruidDataSource;
import com.mashibing.bean.Address;
import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.SQLException;

public class MyTest {
    public static void main(String[] args) throws SQLException {
        ApplicationContext context = new ClassPathXmlApplicationContext("ioc3.xml");
        DruidDataSource dataSource = context.getBean("dataSource", DruidDataSource.class);
        System.out.println(dataSource);
        System.out.println(dataSource.getConnection());
    }
}

4. spring references an external configuration file

Add dbconfig.properties to the resource

username=root
password=123456
url=jdbc:mysql://localhost:3306/demo
driverClassName=com.mysql.jdbc.Driver

Write 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"
       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.xsd">
	<!--Load external profile
		When loading external dependency files context Namespace
	-->
    <context:property-placeholder location="classpath:dbconfig.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${username}"></property>
        <property name="password" value="${password}"></property>
        <property name="url" value="${url}"></property>
        <property name="driverClassName" value="${driverClassName}"></property>
    </bean>
</beans>

5. spring automatic assembly based on xml file

When an object needs to reference another object, we manually configured it through the property tag in the previous configuration. In fact, spring also provides a very powerful function of automatic assembly, which can be configured according to the rules specified by us. The configuration methods are as follows:

default/no: do not auto assemble

byName: assemble according to the name, find the component in the container with the attribute name as the id, and assign a value. If it cannot be found, the assembly will be null

byType: assemble according to the type. Find this component in the container based on the type of the attribute. If there are multiple bean objects of the same type, an exception will be reported. If not found, null will be assembled

Constructor: assemble according to the constructor. First, assemble according to the type of constructor parameters with parameters. If not, directly assemble null; If more than one is found according to the type, the parameter name will be used as the id to continue matching. If it is found, it will be assembled, and if it is not found, it will be assembled null

ioc.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="address" class="com.mashibing.bean.Address">
        <property name="province" value="Hebei"></property>
        <property name="city" value="Handan"></property>
        <property name="town" value="Wu'an"></property>
    </bean>
    <bean id="person" class="com.mashibing.bean.Person" autowire="byName"></bean>
    <bean id="person2" class="com.mashibing.bean.Person" autowire="byType"></bean>
    <bean id="person3" class="com.mashibing.bean.Person" autowire="constructor"></bean>
</beans>

6. Use of spiel

Spiel: Spring expression language, the expression language of spring, supports runtime query of operation objects

Using #{...} as the syntax rule, all characters in braces are considered as spiel

ioc.xml

    <bean id="person4" class="com.mashibing.bean.Person">
        <!--Any operator is supported-->
        <property name="age" value="#{12*2}"></property>
        <!--Other can be referenced bean A property value of-->
        <property name="name" value="#{address.province}"></property>
        <!--Reference other bean-->
        <property name="address" value="#{address}"></property>
        <!--Call static method-->
        <property name="hobbies" value="#{T(java.util.UUID).randomUUID().toString().substring(0,4)}"></property>
        <!--Call non static method-->
        <property name="gender" value="#{address.getCity()}"></property>
    </bean>

Posted by prashanth0626 on Sat, 06 Nov 2021 05:29:31 -0700