IoC configuration in Spring


1. Commonly used IoC annotations and classification

  • Once XML configuration:
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
       scope=""  init-method="" destroy-method="">
      <property name=""  value="" | ref=""></property>
</bean>

1. Used to create objects

Their function is the same as the function realized by writing a tag in the XML configuration file;

@Component

  • Function: used to store the current class object in the spring container;
  • Attribute: value: used to specify the id of the bean. When we don't write, its default value is the current class name, and the first letter is changed to lowercase;

Controller: Generally used in the presentation layer;:
Servicegenerally used in the business layer;:
Repositorygenerally used in the persistence layer;

  • The functions and attributes of the above three annotations are exactly the same as those of Component;
  • The three of them are that the Spring framework provides us with clear annotations for the use of the three layers, making our three-layer objects more clear;

2. Used to inject data

Their role is the same as writing a tag in the bean tag in the xml configuration file;

Autowired

  • Function: Automatically inject according to type. As long as there is only one bean object type in the container that matches the variable type to be injected, the injection can be successful;
  • If there is no bean type in the ioc container that matches the type of the variable to be injected, an error is reported.
  • If there are multiple types of matches in the Ioc container:
    Appearance: It can be a variable or a method
  • Details: When using annotation injection, the set method is not necessary.

Qualifier

  • Function: Inject according to the name on the basis of injection in the class. It cannot be used alone when injecting class members, but it can be used when injecting method parameters;
  • Attribute: value: used to specify the id of the injected bean.

Resource

  • Function: Inject directly according to the bean id. It can be used independently;
  • Attribute: name: used to specify the id of the bean.

Note :

  • The above three injections can only inject data of other bean types;
  • The basic types and String types cannot be implemented using the above annotations.
  • In addition, the injection of collection types can only be achieved through XML.

Value

  • Function: used to inject basic type and String type data;
  • Attribute: value: used to specify the value of the data. It can use SpEL in spring (that is, spring el expression).
    SpEL is written: ${Expression}

3. Used to change the scope of action

Their role is the same as that achieved by using the scope attribute in the bean tag;

Scope

  • Role: used to specify the scope of the bean
  • Attribute: value: the value of the specified range.
    Common values: singleton, prototype;

4. Related to life cycle

Their function is the same as using init-method and destroy-methode in the bean tag;

PreDestroy

  • Role: used to specify the destruction method

PostConstruct

  • Role: used to specify the initialization method

Insert picture description here

2. XML-based IoC configuration

The content of the bean.xml file is 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">
    <!-- 配置Service -->
    <bean id="accountService" class="com.service.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置Dao对象-->
    <bean id="accountDao" class="com.dao.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"></property>
    </bean>

    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatisdata?useUnicode=true&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>

Three, annotation-based IoC configuration

1. Configuration file

(1) The content of the configuration file SpringConfiguration.java is as follows:
(This class is a configuration class, and its function is the same as bean.xml)

@ComponentScan("com")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
    
    

}

(2) The content of the configuration file JdbcConfig.java is as follows:
(This class is a configuration class, which is a class related to Spring database connection)

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

/**
 * 和spring连接数据库相关的配置类
 */
public class JdbcConfig {
    
    

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name="runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
    
    
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name="ds2")
    public DataSource createDataSource(){
    
    
        try {
    
    
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
    
    
            throw new RuntimeException(e);
        }
    }

    @Bean(name="ds1")
    public DataSource createDataSource1(){
    
    
        try {
    
    
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/mybatisdata?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
    
    
            throw new RuntimeException(e);
        }
    }
}

2. New annotations in spring

Configuration

  • Role: Specify that the current class is a configuration class
  • Details: When the configuration class is used as a parameter created by the AnnotationConfigApplicationContext object, the annotation can be omitted.

ComponentScan

  • Function: Used to specify the package that spring will scan when creating a container through annotations
  • Attribute: value: It has the same function as basePackages, both are used to specify the packages to be scanned when creating a container.
    Our use of this annotation is equivalent to configuring in xml:
<context:component-scan base-package="com.itheima"></context:component-scan>

Bean

  • Function: used to store the return value of the current method as a bean object in the spring ioc container
  • Attribute: name: used to specify the id of the bean. When not written, the default value is the name of the current method
  • Details: When we use the annotation configuration method, if the method has parameters, the spring framework will look for available bean objects in the container.
    The search method is the same as the Autowired annotation.

Import

  • Role: used to import other configuration classes
  • Attribute: value: used to specify the bytecode of other configuration classes.
    When we use the Import annotation, the class with Import annotation is the parent configuration class, and all imported are child configuration classes

PropertySource

  • Role: used to specify the location of the properties file
  • Attribute: value: Specify the name and path of the file.
    Keywords: classpath, which means under the classpath

Four, configuration based on xml and annotations

Five, test code

The code link is as follows:
based on xml: code
based on annotation: code

Guess you like

Origin blog.csdn.net/pary__for/article/details/112211949