SSM's Spring Series (3) ---- Spring Annotation-based IoC Detailed Explanation

The functions to be implemented by the annotation configuration and the xml configuration are the same, both of which are to reduce the coupling between the programs. It's just that the form of configuration is different.

Spring annotation-based IoC detailed explanation

  • Let's take a look at the previous XML configuration:
    <bean id="accountService" class="com.cz.service.impl.AccountServiceImpl" scope="" init-method="" destroy-method="">
        <property name="" value="" ref=""></property>

    </bean>

There are multiple tags and attributes in the above XML configuration. As for the purpose of these tags and attributes, you can go to the previous article. Portal

  • Next, Spring's annotation-based IoC is also divided into four categories:
  • Used to create objects:
    • Their <bean>function is the same as the function of writing a tag in an XML configuration file
  • Used to inject data:
    • Their role is the same as <bean>writing a <property>tag in the tag in the XML configuration file .
  • Used to change the scope of action:
    • Their role is the same as the role of <baen>labels in <scope>labels.
  • Related to the life cycle :
    • And their role is in <bean>the use of the label init-methodand destroy-methodthe role is the same.
  • If you want to use annotations, you first need to import the new namespace in the configuration file and specify the packages to be scanned.
<?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="com.cz"></context:component-scan>
</beans>

Annotations used to create objects

相当于:<bean id="" class="">

@Component 注解

  • effect
    • Used to store the current class object in the Spring container
  • Attributes
    • value: Used to specify the unique identifier (Id) of the Bean. If not written, the default value is the current class name, and the first letter is lowercase
  • In addition to @Componentoutside notes, notes there are three derivative is used to create objects, attributes and @Component, as the table below:
Annotation name effect
@Controller Presentation layer
@Service Business Layer
@Repository Persistence layer

  The functions and properties of the three of them are exactly the same as @Repository. These three annotations are the annotations that the Spring framework provides us with clear three-tier usage, making our three-tier objects more clear.
  Details : If there is one and only one attribute to be assigned in the annotation, and the name is value, the value can be omitted in the assignment.

package com.cz.service.impl;

import com.cz.dao.AccountDao;
import com.cz.dao.impl.AccountDaoImpl;
import com.cz.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * 账户的业务层实现类
 */
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
    
    

    private AccountDao accountDao;

    public AccountServiceImpl(){
    
    
        System.out.println("对象创建了");
    }

    public void saveAccount(){
    
    
        accountDao.saveAccount();
        System.out.println("service中的saveAccount方法执行了");
    }
}

Annotations for injecting data

相当于:<property name=" " ref=" "> <property name="" value="">

@Autowired注解

  • effect
    • Automatically inject by type (By Type)
    • The container first uses the variable type to search, if it is in the container 唯一一个 Bean 的类型匹配, then it will be injected directly; if it is not in the container 任何 Bean的类型与要注入的变量类型匹配, then an error will be reported; if it is in the container 有多个 Bean 的类型匹配, the container will be 以变量的名称作为 Bean的id进行查找injected, if a match is found , it will be injected, and if it is not found, an error will be reported.
  • Appearance position
    • Variable or method
  • detail
    • When using annotations to inject properties,set 方法可以省略
/**
 - 账户的业务层实现类
 */
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
    
    

    @Autowired
    private AccountDao accountDao = null;
    //......

For the above annotations, you can look at the picture below:
Insert picture description here
@Qualifier 注解

  • effect

    • In 按照类型注入的基础之上再按照名称注入. It is 给类成员注入时不能单独使用,必须和 @Autowired``一起使用. But it can be used alone when injecting method parameters.
  • Properties
    - value: Bean injection is used to specify the唯一标识 (Id)

/**
 - 账户的业务层实现类
 */
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
    
    

    @Autowired
    @Qualifier("accountDao")
    private AccountDao accountDao = null;
	//.....

@Resource 注解

  • effect

    • Automatically follow 名称注入(By Name), inject directly according to the Bean's Id, it can be used independently.
  • Attributes

    • name : Specify the id of the injected Bean
/**
 * 账户的业务层实现类
 */
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
    
    

//    @Autowired
//    @Qualifier("accountDao")
    @Resource(name = "accountDao")
    private AccountDao accountDao = null;

The above three annotations can only inject data of other Bean types, and the basic types and String types need to use the following annotations. In addition, the injection of collection types can only be achieved through XML .

@Value 注解

  • effect
    • injection基本类型和 String 类型数据
  • Attributes
    • value: Used to specify the value of the data. It can use Spring's SpEL (Spring's el expression, written in:${表达式})

Used to change the scope of action

相当于:<bean id="" class="" scope="">

@Scope 注解

  • effect
    • Specify the scope of the bean
  • Attributes
    • value: The value of the specified range. Commonly used value issingleton、prototype

Related to life cycle

相当于:<bean id="" class="" init-method="" destroy-method="" />

@PreDestroy 注解

  • effect
    • Used to specify the destruction method

PostConstruct 注解

  • effect
    • Used to specify the initialization method
@PostConstruct
public void init() {
    
    
    System.out.println("初始化方法执行了");
}

@PreDestroy
public void destroy() {
    
    
    System.out.println("销毁方法执行了");
}

Comparison of XML and annotation methods

  • Advantages of annotations
    • Simple configuration and easy maintenance
  • Advantages of XML
    • There is no need to modify the source code when modifying, and does not involve recompilation and deployment

Comparison of Spring Management Bean:

XML-based configuration Configuration based on annotations
Bean definition <bean id = "..." class = "..." /> @Component、@Controller、@Service、@Repository
Bean name By idor nameattribute specifies @Component("user")
Bean injection By <property>or <constructor-arg>label injection @Autowired、@Qualifier、@Resource
Bean scope scopeSpecified by attribute @Scope
Bean life cycle By init-methodor destroy-methodattribute specifies the initialization and destruction methods @PostConstruct、@PreDestroy
Bean is suitable for the scene Bean comes from a third party and cannot modify the source code The implementation class of Bean is developed by ourselves

This is the end of Spring's annotation-based IoC. Next, I will look at the difference between XML implementation and annotation implementation in the same case.

Guess you like

Origin blog.csdn.net/weixin_43844418/article/details/113770738