Spring - IoC core (based on XML), DI core (based on XML)

Catalog

1, IoC container

Jump to directory
I have introduced the idea of IoC in the last article, and I will not repeat it here!

Spring IoC container:

  • BeanFactory: the lowest interface of spring, which only provides IoC functions and is responsible for creating, assembling and managing beans. Therefore, BeanFactory is generally not applicable. ApplicationContext (application context) is recommended

  • ApplicationContext: the ApplicationContext interface inherits BeanFactory, and also provides functions such as AOP inheritance, internationalization processing, event propagation, and unified resource value; you can view the inheritance system of the interface;

1. The difference between BeanFactory and ApplicationContext

Jump to directory
Beans are created at different times:

  • BeanFactory has the feature of delayed initialization (lazy loading). When creating a Spring container, you do not immediately create the container and manage the Bean objects, but wait until you get the objects from the container to create the objects

  • When ApplicationContext creates a Spring container, it initializes the Bean managed in the container immediately, rather than waiting for the Bean to be obtained

// Person
@Data
public class Person {
    private String name;
    private int age;

    public Person(){
        System.out.println("Person Object created!");
    }
}

// person.xml
<!-- Use IoC To manage object creation and dependency injection-->
<bean id="person" class="com.sunny.domain.Person">
    <property name="name" value="CoderZYGui"/>
    <property name="age" value="23"/>
</bean>

// Person test (not Spring Test)
public class PersonTest {

    // Creating Spring IoC containers with BeanFactory
    /**
     * --------------------------------
     * Person Object created!
     * Person(name=CoderZYGui, age=23)
     *
     * Conclusion: BeanFactory has the feature of delayed initialization (lazy loading). When creating Spring containers, you will not create them immediately,
     *      Manage Bean objects, but wait until you get them from the container to create them
     */
    @Test
    public void test1(){
        Resource resource = new ClassPathResource("xmls/person.xml");
        BeanFactory factory = new XmlBeanFactory(resource);
        System.out.println("--------------------------------");
        Person person = factory.getBean("person", Person.class);
        System.out.println(person);
    }

    // Using ApplicationContext to create Spring IoC container
    /**
     * Person Object created!
     * --------------------------------
     * Person(name=CoderZYGui, age=23)
     *
     * Conclusion: when creating a Spring container, the Bean managed in the container will be initialized immediately, rather than waiting for the Bean to be obtained
     */
    @Test
    public void test2(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("xmls/person.xml");
        System.out.println("--------------------------------");
        Person person = ctx.getBean("person", Person.class);
        System.out.println(person);
    }

2. Four ways to instantiate a Bean

Jump to directory

  • Constructor instantiation (no parameter constructor), most used
  • Static factory method instantiation (understand)
  • Instance factory method instantiation (understand)
  • Implement FactoryBean interface instantiation: a variation of instance factory
2.1. Instantiate with constructor (no parameter constructor)

Jump to directory

// class
public class Cat1 {
    public Cat1(){
        System.out.println("structure Cat1");
    }
}

// createBean.xml
<!--1,Constructor instantiation(Parameterless constructor),Most used-->
<bean id="cat1" class="com.sunny.createbean._01_constructor.Cat1"/>
2.2. Static factory method instantiation (understanding)

Jump to directory

/ / class
public class Cat2 {
}
//Cat2 factory
public class Cat2Factory {
    public static Cat2 createInstance(){
        Cat2 cat2 = new Cat2();
        return cat2;
    }
}

// createBean.xml
 <! -- 2. Static factory method instantiation (understand)
        Previously, the static factory method was used: Cat2 cat2 = Cat2Factory.createInstance(); to create,
        Now it's just a matter of setting this way into the configuration file
-->
<bean id="cat2" class="com.sunny.createbean._02_static_factory.Cat2Factory"
        factory-method="createInstance"/>
2.3 instance factory method instantiation (understanding)

Jump to directory

/ / class
public class Cat3 {
}
//Cat3 factory
public class Cat3Factory {

    public Cat3 createInstance(){
        Cat3 cat3 = new Cat3();
        return cat3;
    }
}

// createBean.xml
 <! -- 3. Instance factory method instantiation (understand)
        The first bean is to create the instance factory object, and the second bean is to call the factory method to create the Cat3 object through the instance factory object
-->
<bean id="cat3Factory" class="com.sunny.createbean._03_instance_factory.Cat3Factory"/>
<bean id="cat3" factory-bean="cat3Factory" factory-method="createInstance"/>
2.4. Implement FactoryBean interface instantiation

Jump to directory

// class
public class Cat4 {
}
// Cat4 factory
public class Cat4Factory implements FactoryBean<Cat4> {
    private String name;
    
    public void setName(String name) {
        this.name = name;
    }

    // Example factory method (compared with method 3, which fixes the factory instance method)
    public Cat4 getObject() throws Exception {
        System.out.println("name=:" + name);
        Cat4 cat4 = new Cat4();
        return cat4;
    }

    public Class<?> getObjectType() {
        return Cat4.class;
    }
}

// createBean.xml
<!--4,Realization FactoryBean Interface instantiation:Variations of the example factory
    Cat4Factory The method of creating instance of factory class has been implemented fixedly,Cat4Factory Through the implementation method getObject come
        //Create Cat4's object
-->
<bean id="cat4" class="com.sunny.createbean._04_factory_bean.Cat4Factory">
    <property name="name" value="Cat 4"/>
</bean>

test

Spring test (junit4 based)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunit4 {

    // @Autowired: means to find the corresponding bean from the Spring IoC container according to the type and inject it to a field automatically
    // -------Four ways to instantiate a Bean---------
    @Autowired
    private Cat1 cat1;
    @Autowired
    private Cat2 cat2;
    @Autowired
    private Cat3 cat3;
    @Autowired
    private Cat4 cat4;

    // When you don't use the Spring container, use the instantiation steps of these four methods
    @Test
    public void testOld() throws Exception {
        // Instantiate bean s using constructor
        Cat1 cat1 = new Cat1();
        // Instantiate the bean using the static factory method
        Cat2 cat2 = Cat2Factory.createInstance();
        // Instantiate the bean using the instance factory method
        Cat3 cat3 = new Cat3Factory().createInstance();
        // Implement factory bean interface instantiation
        Cat4 cat4 = new Cat4Factory().getObject();
    }
    @Test
    public void test2(){
        System.out.println(cat1);
        System.out.println(cat2);
        System.out.println(cat3);
        System.out.println(cat4);
    }
}

3. Bean scope

Jump to directory
In the Spring container, it refers to the visible range of the created Bean object relative to other Bean objects. Syntax format:

<bean id="" class="" scope="Scope of action"/>
  • singleton: single instance. There is only one Bean instance in the Spring IoC container (the default is scope)
  • prototype: multi Li, each time calling Bean from the container, returns a new instance. When calling getBean() each time, it is equivalent to executing new XxxBean(), and it will not create objects when the container starts.

Other

/ / class
public class Dog {
}

// Dog.xml
 <! -- bean's scope,
    Single example: the default is singleton, and all the objects obtained from the container are the same object
    Multiple examples: prototype, the object obtained from the container is not the same object
-->
<bean id="dog" class="com.sunny.scope.Dog" scope="singleton"/>

// Spring Test
 //Scope scope of the-----------------
//Represents an instantiated dog object taken from the container
@Autowired
private Dog dog1;
@Autowired
private Dog dog2;

@Test
public void test3(){
    //Because the scope of the bean is singleton by default, the Dog object generated by the container is the same
    System.out.println(dog1);
    System.out.println(dog2);
}

4. Bean initialization and destruction

Jump to directory
For example, DataSource and SqlSessionFactory all need to close the asset at last; the close method must be called before the Bean is destroyed, and in the Spring IoC container, it can help us manage the creation of the object. How can we manage the initialization and recycling operations of the object after creation? The syntax is as follows:

<bean id="" class="" init-method="Class initialization method name"
     destroy-method="Name of such destruction method"/>
  • Init method: call the initialization method of ds object, and execute immediately before initialization
  • Destroy method: call the destroy method of ds object, and call
Operation when using Spring IoC container

The test uses Spring Test

MyDataSource class

/**
 * Simulate database connection pool
 * When the connection pool is used, it needs to be initialized and destroyed. After using the Spring IoC container, how to
 * Let containers help us initialize and destroy?
 */
public class MyDataSource {

    public MyDataSource(){
        System.out.println("create object...");
    }

    public void open(){
        System.out.println("Open resources...");
    }

    public void close(){
        System.out.println("Destruction of resources...");
    }

    public void doWork(){
        System.out.println("work...");
    }
}

// mydatasource.xml
<!--
    init-method: call ds Object initialization method,Before initialization execution,Immediate execution
    destroy-method: call ds Destruction method of objects,Before destruction execution,call
-->
<bean id="ds" class="com.sunny.lifecycle.MyDataSource" init-method="open"
    destroy-method="close"/>

//Spring Test test
// ------bean initialization and destruction--------
// Operation without Spring container
@Test
public void testOld1(){
    // create object
    MyDataSource ds = new MyDataSource();
    System.out.println("-------");
    // Initialize operation
    ds.open();
    // work
    ds.doWork();
    // Destruction
    ds.close();
}
// How to use Spring container
@Autowired
private MyDataSource ds;

@Test
public void test4(){
    ds.doWork();
}

Use common test methods
The destruction resources are not printed out here, which is the difference between common test and Spring test;

  • Spring testing will release resources normally
  • Normal unit tests do not release resources normally, so you need to release resources manually

xml files are the same as classes

public class MyDataSourceTest {
    /**
     * The destruction resources are not printed out here, which is the difference between common test and Spring test;
     * Spring Testing will release resources normally
     * Normal unit tests do not release resources normally, so you need to release resources manually
     */
    @Test
    public void test(){
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("xmls/mydatasource.xml");
        MyDataSource ds = ctx.getBean("ds", MyDataSource.class);
        ds.doWork();
        ds.close(); // Release resources manually
    }

    @Test
    public void test1(){
        @Cleanup //Use the Clearup annotation in lombok, a third-party framework, to release
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("xmls/mydatasource.xml");
        MyDataSource ds = ctx.getBean("ds", MyDataSource.class);
        ds.doWork();
    }

    @Test
    public void test2(){
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("xmls/mydatasource.xml");
        MyDataSource ds = ctx.getBean("ds", MyDataSource.class);
        ds.doWork();
        // This way is to use the Spring thread as a sub thread of the JVM. When the JVM is closed, the Spring thread will also be closed
        ctx.registerShutdownHook();
    }
}

5. Instantiation process of Bean

Jump to directory
Bean declaration cycle: the whole process of bean destruction from birth

<bean id="" class="" init-method="Class initialization method name"
     destroy-method="Name of such destruction method"/>

1. Start the Spring container
2. Create Bean object
3. Add properties to a Bean
4. Call init method of Bean object
5. getBean gets a bean object and calls a method of the bean object
6. Call destroy method of Bean object
7. Spring container destruction

2, DI operation

Jump to directory

1. What is an injection operation?

Jump to directory

Injection mode:

  • setter method injection
  • Constructor Injection

Injection value type:

  • Constant value (simple type) ---- value element
  • Object ----- ref element
  • Collection ----- object collection type element

2. XML autoassemble (not recommended)

Jump to directory

  • Set the: autowire attribute of the < bean / > element
        <bean id="person2" class="Person Full name of" autowire="byName"/>
    
  • autowire property: let Spring find the right object by itself according to certain rules, and complete the DI injection operation

    Be careful:
    • If byName is used for automatic injection, all attribute names and id names must be named in a standard way
    • If byType injection is installed, if there are multiple instances of the same type in the Spring container, the report bean is not the only type error;
// Requirement: let Spring help us create the Person object, which also depends on the Dog object; so we need to create two beans
public class Person {
    private Dog dog;

    public void setDog(Dog dog){
        this.dog = dog;
    }
    @Override
    public String toString() {
        return "Person{" + "dog=" + dog + '}';
    }
}

// .xml
<bean id="dog1" class="com.sunny._01_xml_autowired.Dog"/>
<bean id="person2" class="com.sunny._01_xml_autowired.Person" autowire="byName"/>

// Spring Test test
// @Autowired: means to find the corresponding bean from the Spring IoC container according to the type and inject it to a field automatically
@Autowired
private Person person;

@Test
public void test(){
    System.out.println(person);
}

3. Setter method injection (key)

Jump to directory

3.1 injection constant

Jump to directory
Injection constant value, also known as injection simple type:

<property name="Object property name" value="Injected value"/>
// class
@Setter
@ToString
public class Employee {
    private String name;
    private Integer age;
    private BigDecimal salary;
}

3.2 injection object

Jump to directory
To inject an object is to set one object to another through the setter method:

<property name="Object property name" ref="Of the injected object bean Of id"/>
// class
public class Cat {
}
public class Person {
    private Cat c1;
    public void setC1(Cat c1) {
        this.c1 = c1;
    }
    @Override
    public String toString() {
        return "Person1{" +
                "c1=" + c1 +
                '}';
    }
}

3.3 injection set

Jump to directory
To inject a collection is to set the data of a collection type to another object through the setter method:

 <property name="Collection type">
            <set>
                <value>set1</value>
                <value>set2</value>
            </set>
 </property>
// class
@Setter
public class CollectionBean {
    private Set<String> set;
    private List<String> list;
    private String[] array;
    private Map<String, String> map;
    private Properties prop;

    @Override
    public String toString() {
        return "CollectionBean{" +
                "\nset=" + set +
                ", \nlist=" + list +
                ", \narray=" + Arrays.toString(array) +
                ", \nmap=" + map +
                ", \nprop=" + prop +
                '}';
    }
}

XML file

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

    <!--Attribute injection: Injection constant type-->
    <bean id="employee" class="com.sunny._02_di_setter.Employee">
        <property name="name" value="coder"/>
        <property name="age" value="23"/>
        <property name="salary" value="188.00"/>
    </bean>

    <!--Attribute injection: Injection object type-->
    <bean id="cat" class="com.sunny._02_di_setter.Cat"/>
    <bean id="person" class="com.sunny._02_di_setter.Person">
        <property name="c1" ref="cat"/>
    </bean>

    <!--Attribute injection: Injection set type-->
    <bean id="collectionBean" class="com.sunny._02_di_setter.CollectionBean">
        <!--set type-->
        <property name="set">
            <set>
                <value>set1</value>
                <value>set2</value>
            </set>
        </property>
        <!--list type-->
        <property name="list">
            <list>
                <value>list1</value>
                <value>list2</value>
            </list>
        </property>
        <!--array type-->
        <property name="array">
            <array>
                <value>array1</value>
                <value>array2</value>
            </array>
        </property>
        <!--map type-->
        <property name="map">
            <map>
                <entry key="key1" value="value1"/>
                <entry key="key2" value="value2"/>
            </map>
        </property>
        <!--properties type-->
        <!--<property name="prop">
            <props>
                <prop key="key1">value1</prop>
                <prop key="key2">value2</prop>
            </props>
        </property>-->
        <property name="prop">
            <value>
                k1=v1
                k2=v2
                k3=v3
            </value>
        </property>
    </bean>
</beans>


Test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class DiSetterTest {
    // @Autowired: means to find the corresponding bean from the Spring IoC container according to the type and inject it to a field automatically
    @Autowired
    private Employee employee;
    @Autowired
    private Person person;
    @Autowired
    private CollectionBean cb;

    @Test
    public void test1(){
        System.out.println(employee);
        System.out.println(person);
        System.out.println(cb);
    }
}

output

4. Constructor injection

Jump to directory

  • setter mode injection uses < property / > elements
  • Constructor mode injection uses the < constructor Arg / > element

    Class Java
// Injected constant class
@ToString
@AllArgsConstructor
public class Employee1 {
    private String name;
    private Integer age;
    private BigDecimal salary;
}
// Class of injection object
public class Cat1 {
}
public class Person1 {
    private Cat1 c1;
        public Person1(Cat1 c1) {
        this.c1 = c1;
    }
    @Override
    public String toString() {
        return "Person1{" +
                "c1=" + c1 +
                '}';
    }
}
// Inject a class of collection type
@AllArgsConstructor //Generate full parameter constructor
@ToString
public class CollectionBean1 {
    private Set<String> set;
    private List<String> list;
    private String[] array;
    private Map<String, String> map;
    private Properties prop;
}

xml file

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

    <!--Constructor Injection : constant type-->
    <bean id="employee1" class="com.sunny._03_di_constructor.Employee1">
        <constructor-arg name="name" value="zygui"/>
        <constructor-arg name="age" value="23"/>
        <!--<constructor-arg name="salary" value="9999.00"/>-->
        <constructor-arg name="salary">
            <null/>
        </constructor-arg>
    </bean>

    <!--Constructor Injection : object type-->
    <bean id="cat1" class="com.sunny._03_di_constructor.Cat1"/>
    <bean id="perosn1" class="com.sunny._03_di_constructor.Person1">
        <constructor-arg name="c1" ref="cat1"/>
    </bean>

    <!--Constructor Injection : Collection type-->
    <bean id="collectionBean1" class="com.sunny._03_di_constructor.CollectionBean1">
        <!--set type-->
        <constructor-arg name="set">
            <set>
                <value>set1</value>
                <value>set2</value>
            </set>
        </constructor-arg>
        <!--list type-->
        <constructor-arg name="list">
            <list>
                <value>list1</value>
                <value>list2</value>
            </list>
        </constructor-arg>
        <!--array type-->
        <constructor-arg name="array">
            <array>
                <value>array1</value>
                <value>array2</value>
            </array>
        </constructor-arg>
        <!--map type-->
        <constructor-arg name="map">
            <map>
                <entry key="key1" value="value1"/>
                <entry key="key2" value="value2"/>
            </map>
        </constructor-arg>
        <!--properties type-->
        <constructor-arg name="prop">
            <value>
                k1=v1
                k2=v2
                k3=v3
            </value>
        </constructor-arg>
    </bean>
</beans>

Test class

    // @Autowired: means to find the corresponding bean from the Spring IoC container according to the type and inject it to a field automatically
    @Autowired
    private Employee1 emp;
    @Autowired
    private Person1 p1;
    @Autowired
    private CollectionBean1 cb1;

    @Test
    public void test1(){
        System.out.println(emp);
        System.out.println(p1);
        System.out.println(cb1);
    }

5. Bean element inheritance

Jump to directory
Extraction of common configuration of multiple bean elements is actually a copy of bean configuration, which is different from Java inheritance

  • Java inheritance: extracting the common code of multiple classes into the parent class
  • Inheritance of bean elements: extract the common attribute configuration of multiple bean elements into another common bean element

Class Java

@Setter
@ToString
public class SomeBean1 {
    private String name;
    private Integer age;
    private Double weight;
}

@Setter
@ToString
public class SomeBean2 {
    private String name;
    private Integer age;
    private Double height;
}

xml configuration

<?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">
    
    <!--Multiple bean Extraction of common configuration-->
    <bean id="baseBean" abstract="true">
        <property name="name" value="Tom"/>
        <property name="age" value="23"/>
    </bean>

    <bean id="someBean1" class="com.sunny._04_bean_tag_inheritance.SomeBean1" parent="baseBean">
        <!--Can cover-->
        <property name="name" value="lucy"/>
        <property name="weight" value="60.0"/>
    </bean>
    <bean id="someBean2" class="com.sunny._04_bean_tag_inheritance.SomeBean2" parent="baseBean">
        <property name="height" value="175.0"/>
    </bean>

    
    <!--Primitive writing,No use Bean Inheritance-->
    <!--<bean id="someBean1" class="com.sunny._04_bean_tag_inheritance.SomeBean1">
        <property name="name" value="Tom"/>
        <property name="age" value="23"/>
        <property name="weight" value="60.0"/>
    </bean>
    <bean id="someBean2" class="com.sunny._04_bean_tag_inheritance.SomeBean2">
        <property name="name" value="Tom"/>
        <property name="age" value="23"/>
        <property name="height" value="175.0"/>
    </bean>-->
</beans>

6. Property placeholder

Jump to directory
Take an example of querying a database:

  • Table structure
CREATE TABLE `student` (
  `id` bigint(20) NOT NULL,
  `name` varchar(40) NOT NULL,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1. Original version
  • Test method of querying database information
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class PropertyPlaceholderTest {
    private DruidDataSource ds;

    @Test
    public void test() throws Exception{
        ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/spring");
        ds.setUsername("root");
        ds.setPassword("1111");
        ds.setInitialSize(2);

        @Cleanup
        Connection conn = ds.getConnection();
        String sql = "SELECT id, name, age FROM student";
        @Cleanup
        PreparedStatement ps = conn.prepareStatement(sql);
        @Cleanup
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            System.out.print(rs.getLong("id")+",");
            System.out.print(rs.getString("name")+",");
            System.out.println(rs.getInt("age"));
        }
    }
}

Note: @ Cleanup is the annotation of lombok, a third-party framework. The function of this annotation is to automatically manage resources and handle some exceptions

Successfully queried information in database

However, from the above code, we can find that we can give this piece of code to the Spring IoC container to handle, let IoC build our dataSource object, let DI inject property values into this object;

2. Spring IoC container management version
  • Test class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class PropertyPlaceholderTest {

    // @Autowired: means to find the corresponding bean from the Spring IoC container according to the type and inject it to a field automatically
    @Autowired
    private DruidDataSource ds;

    @Test
    public void test() throws Exception{
        @Cleanup
        Connection conn = ds.getConnection();
        String sql = "SELECT id, name, age FROM student";
        @Cleanup
        PreparedStatement ps = conn.prepareStatement(sql);
        @Cleanup
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            System.out.print(rs.getLong("id")+",");
            System.out.print(rs.getString("name")+",");
            System.out.println(rs.getInt("age"));
        }
    }
}
  • db.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=1111
jdbc.initialSize=2
  • xml 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">

    <!--from classpath Root path to load db.properties file-->
    <!--<context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--Configure one druid Connection pool-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
    </bean>

    <!-- Write about death -->
    <!--<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="1111"/>
        <property name="initialSize" value="2"/>
    </bean>-->

</beans>

Be careful:
To add context namespace to xml file

<! -- load the db.properties file from the root path of the classpath -- >
<context:property-placeholder location="classpath:db.properties"/>
182 original articles published, praised 129, visited 140000+
Private letter follow

Tags: Spring xml JDBC Attribute

Posted on Wed, 11 Mar 2020 23:31:40 -0700 by rashmi_k28