Spring basic usage and dependency injection

The Spring framework is the most commonly used framework in java development. It is very powerful. Official website: https://spring.io

Several core concepts of the Spring framework:

  • IoC: Inversion of Control, inversion of control (control of object creation is transferred to Spring)
  • DI: Dependency Injection, dependency injection
  • AOP: Aspect Orientend Programming, aspect-oriented programming

1. Without IoC, you need to manually create and introduce related object instances. The structure is as follows:

  • Create factory.properties file to configure related classes
  • Create a factory class, the factory class loads the configuration file, and then instantiates and returns the required objects

2. After introducing Spring's IoC:

  • No need to manually create objects for reference. Spring will automatically create objects according to the agreed configuration. In fact, it acts as a factory method for decoupling. After importing the logback-classic framework, you can see more details.
  • First, configure a Spring xml file, as follows:
<?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="personDao" class="com.mj.dao.impl.PersonDaoImpl"/>
    <bean id="personService" class="com.mj.service.impl.PersonServiceImpl">
        <property name="dao" ref="personDao"/>
    </bean>
    <bean id="personServlet"  class="com.mj.servlet.PersonServlet">
        <property name="service" ref="personService"/>
    </bean>

</beans>
  • Then you need to set the set method of service and dao. The above configuration file is assigned according to the set method.
public class PersonServlet {

//    PersonService service = PersonFactory.getService();
    PersonService service;

    public void setService(PersonService service) {
        this.service = service;
    }

    private void remove(){
        service.remove(1);
    }
    public static void main(String[] args) {

        // 读取配置文件
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        PersonServlet servlet = ctx.getBean("personServlet",PersonServlet.class);
        servlet.remove();
    }
}

3. Dependency Injection 

Commonly used injection content can be divided into the following three types

  • bean custom type
  • Basic types: String, Interger, etc.
  • Collection types (Array, Map, List, Set, Properties)

There are two common injection methods

  • Based on setter (property)
  • Constructor-based

Set method injection: 

 <bean id="personServlet"  class="com.mj.servlet.PersonServlet">
        <property name="service" ref="personService"/>
    </bean>
public class PersonServlet {

    PersonService service;

    public void setService(PersonService service) {
        this.service = service;
    }
}

 The above is dependency injection, servlet depends on sevice, and it is automatically injected after configuration.

The following injections are the same dog object:


    <bean id="dog" class="com.mj.domain.Dog"/>

    <bean id="person" class="com.mj.domain.Person">
        <property name="name" value="小马哥"/>
        <property name="age" value="12"/>
        <property name="dog" ref="dog"/>
    </bean>
    
    <bean id="student" class="com.mj.domain.Student">
        <property name="dog" ref="dog"/>
    </bean>

The following injections are different dog objects:

 <bean id="person" class="com.mj.domain.Person">
        <property name="dog">
            <bean class="com.mj.domain.Dog"/>
        </property>
    </bean>

    <bean id="student" class="com.mj.domain.Student">
        <property name="dog">
            <bean class="com.mj.domain.Dog"/>
        </property>
    </bean>

Here is the injection of an array of strings:

 <bean id="person" class="com.mj.domain.Person">
        <property name="name" value="小马哥"/>
        <property name="age" value="12"/>
        <property name="dog">
            <bean class="com.mj.domain.Dog"/>
        </property>
        <property name="nickNames" >
            <array>
                <value>damage</value>
                <value>小马哥</value>
                <value>大神</value>
            </array>
        </property>
        <property name="maps">
            <map>
                <entry key="key1" value="value1"/>
                <entry key="key2" value="value2"/>
                <entry key="key3" value="value3"/>
            </map>
        </property>
    </bean>

Constructor injection:

  <bean id="person" class="com.mj.domain.Person">
        <constructor-arg index="0" value="18"/>
        <constructor-arg index="1" value="我是小马哥"/>
        <constructor-arg>
            <bean class="com.mj.domain.Dog"/>
        </constructor-arg>
    </bean>

Method injection:

factory:

public class ConnectionFactory {
    public static Connection getConn() throws Exception {
//        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","123456");
    }

    public  Connection getInstanceConn() throws Exception {
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","123456");
    }

}

applicationContext.xml file:

  <!--  静态工厂方法(调用ConnectionFactory,getConn())  -->
    <bean id="conn" class="com.mj.obj.ConnectionFactory" factory-method="getConn"/>
    <!--实例工厂方法-->
    <bean id="factory" class="com.mj.obj.ConnectionFactory">
        <property name="dirverClass" value="xxxx"/>
        <property name="password" value="xxx"/>
        <property name="username" value="xxx"/>
        <property name="url" value="xxx"/>
    </bean>
    <bean id="instanceConn" factory-bean="factory" factory-method="getInstanceConn"/>

Test class:

 @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println(context.getBean("conn"));
        System.out.println(context.getBean("instanceConn"));
    }

scope

Whether the bean is a singleton can be controlled by the scope attribute

  • singleton: singleton; through the same id value, the same instance will always be obtained in an IoC container; when the IoC container is created, a bean will be created, and lazy-init can be set to true to modify the creation time
  • prototype: non-singleton, create a bean every time you getBean
<bean id="dog" class="com.mj.domain.Dog" scope="singleton" lazy-init="true"/>

Note the username reserved field: 

converter:

The built-in converter can complete some functions. For example, the following date can only use the type of 2011/09/23 . If you use 2011-09-23 , an error will be reported. At this time, we need to customize the converter

 <bean id="person" class="com.mj.domain.Person">
        <property name="date" value="2011/05/30"/>
    </bean>

 Write a conversion class:

package com.mj.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String, Date> {
    private String format;

    public void setFormat(String format) {
        this.format = format;
    }

    public Date convert(String s) {
        SimpleDateFormat fmt = new SimpleDateFormat(format);
        try {
            return fmt.parse(s);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

xml file configuration:

Pay attention to details: the id when configuring FactoryBean should be fixed as conversionService

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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="person" class="com.mj.domain.Person" p:date="09_10_2010"/>

    <!--配置FactoryBean id要固定为conversionService-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.mj.converter.DateConverter" p:format="yyyy-MM-dd"/>
                <bean class="com.mj.converter.DateConverter" p:format="MM_dd_yyyy"/>
            </set>
        </property>
    </bean>

</beans>

Guess you like

Origin blog.csdn.net/weixin_45689945/article/details/127122796