Spring IOC&DI based on annotation method

1 Configure the annotation of the bean

1.1 Scanning annotations

To configure the bean using annotations, you must add package scanning in the spring 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">

    <!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
    context名称空间和约束中-->
    <context:component-scan base-package="service"></context:component-scan>
    <context:component-scan base-package="dao"></context:component-scan>
</beans>

1.2 @Component and its derivative annotations

@Component is used to configure the bean, and the annotated class is actually equivalent to using the bean tag in the Spring configuration file.

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

@Controller: Generally used in the presentation layer

@Service: Generally used in the business layer

@Repository: Generally used in the persistence layer

The above three annotations are the same as @Component, but the semantics are clearer.

1.3 Annotation of Dependency Injection

There are four common annotations for dependency injection:

@Autowired:

  • Function: Automatically inject according to the type, as long as there is only one bean object type in the container that matches the type of the variable to be injected, the injection can be successful;
  • Location: variable, or method
  • note:
    • If there is no bean type matching it in the container, an error will be reported;
    • When there are multiple types matching in the container, if the variable name is the same as the bean id, the bean will be used; if not, an error will be reported.

@Qualifier:

  • Function: Inject according to the name on the basis of the injection in the class, and use it with @Autowired
  • Attributes:
    • value: used to specify the id of the injected bean.

@Resource

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

@Value

  • Role: used to inject basic type and String type data
  • Attributes:
    • value: Used to specify the value of the data. It can use SpEL in spring (that is, spring el expression)
    • How to write SpEL: ${Expression}

1.4 Scope

The annotation to set the scope of the bean is @Scope
@Scope

  • Role: used to specify the scope of the bean
  • Attributes:
    • value: The value of the specified range. Common values: singleton, prototype
  • Location: Act on the class or method, specify the scope of the bean

1.5 Life cycle

There are two annotations specifying the life cycle @PostConstruct and @PreDestroy, both of which are written on the method

  • @PostConstruct

    • Role: used to specify the initialization method
  • @PreDestroy

    • Role: used to specify the destruction method

2 Annotation of the configuration file

2.1 Detailed annotations

Using the following annotations, you can achieve true "zero configuration": including @Configuration, @ComponentScan, @Bean, @Import, @PropertySource

@Configuration

  • Function: Specify that the current class is a configuration class, which is equivalent to Spring's configuration xml file

@ComponentScan

  • Function: Specify the package that Spring will scan when creating the container, which is equivalent to the tag <context:component-scan base-package="">
  • Attributes:
    • Value: It has the same function as basePackages, both of which are used to specify the packages to be scanned when the container is created.

@Bean

  • Function: used to take the return value of the current method as a bean object and store it in the spring container
  • Attributes:
    • name: used to specify the id of the bean, when not written, the default value is the name of the current method
  • Note: If the method has parameters, it will go to the container to find out if there is a bean object available. The search method is the same as the function of Autowired annotations.

@Import

  • Role: used to import other configuration classes
  • Attributes:
    • value: The bytecode used to specify other configuration classes.
  • Note: When we use the Import annotation, the class with Import annotation is the parent configuration class, and the imported are all sub-configuration classes

@PropertySource

  • Role: used to specify the location of the properties file
  • Attributes:
    • value: Specifies the name and path of the file.
      Keyword: classpath, which means under the class path

2.2 Case

package config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;

@Configuration
@ComponentScan(basePackages = {
    
    "dao","service"})
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
    
    

    @Bean(name="runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(@Qualifier("dataSource1") DataSource dataSource){
    
    
        return new QueryRunner(dataSource);
    }
}

3 "Zero Configuration" Case

This case prepares a controller class, a service class, a Dao class and a configuration class.

3.1 pom file

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
    </dependencies>

3.2 Configuration file class

package com.lrm.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {
    
    "com.lrm"})
public class SpringConfig {
    
    
}

3.3 dao class

package com.lrm.dao;

import org.springframework.stereotype.Repository;

@Repository(value = "userDaoImpl")
public class UserDaoImpl implements UserDao {
    
    
    @Override
    public void add() {
    
    
        System.out.println("dao add.....");
    }
}

3.4 service class

package com.lrm.service;

import com.lrm.dao.UserDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService {
    
    

    @Value(value = "abc")
    private String name;

//    @Autowired  //根据类型进行注入
//    @Qualifier(value = "userDaoImpl") //根据名称进行注入
//    private UserDao userDao;

    //@Resource  //根据类型进行注入
    @Resource(name = "userDaoImpl")  //根据名称进行注入
    private UserDao userDao;

    public void add() {
    
    
        System.out.println("service add......."+name);
        userDao.add();
    }
}

3.5 Controller class

package com.lrm.controller;

import com.lrm.config.SpringConfig;
import com.lrm.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserController {
    
    

    @Test
    public void test1() {
    
    
        //加载配置类
        ApplicationContext context
                = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }
}

Guess you like

Origin blog.csdn.net/Orange_minger/article/details/114606986