Spring5 Study Notes (6) — "IOC Operation Bean Management (Annotation-based)"

IOC operation Bean management (based on annotation)


1. What is an annotation

​ (1) Annotation is a special code mark

Format: @ annotation name (property name=property value, property name=property value...)

​ (2) Use annotations, which are used in类上面,方法上面,属性上面

(3) The purpose of using annotations:简化 xml 配置

2. Spring provides annotations for Bean management operations

1. The following four annotations have the same function and can be used to create bean instances

  • @Component
  • @Service
  • @Controller
  • @Repository

2. The following four annotations can be used to inject properties into objects

  • @Autowired: Inject according to attribute type
  • @Qualifier: Inject by property name
  • @Resource: It can be injected according to the attribute type, or it can be injected according to the attribute name
  • @Value: Inject normal type properties

The first three are injected 对象类型properties

3. IOC operation bean management (based on annotations)

1. Create objects based on annotations

Step 1: Import the jar package (the Spring-related jar package can be automatically imported into the project directly through the idea)
insert image description here
Step 2: Enable component scanning (in the Spring configuration file)
by <context:component-scan> </context:component-scan>implementing

<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">
        <!--上方引入context名称空间(第3、5行)-->

    <!--开启组件扫描
        如要扫描多个同包类:
        1.base-package属性中的多个包类路径,用逗号隔开
        2.base-package属性值直接写这几个类的共同“上层包”的名
    -->
    <context:component-scan base-package="demo1"></context:component-scan>
</beans>

Step 3: Create a Book class and use annotations to create objects

import org.springframework.stereotype.Component;

/*
可以直接写@Component
即value值省略不写
(默认值为类名,首字母小写,例如:book)
*/
@Component("book") //注解等同于配置文件中<bean id="book" class="...">
public class Book {
    
    
    public void test(){
    
    
        System.out.println("book test............");
    }
}

The fourth step is to write the test class

public class bookTest {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext context = 
        new ClassPathXmlApplicationContext("demo1/bean1.xml");
        Book book = context.getBean("book",Book.class);
        book.test();
    }
}

Small details : Turn on component scanning details configuration (you can understand it)

<!--示例 1
 use-default-filters="false" 表示现在不使用默认 filter,自己配置 filter
 context:include-filter ,设置扫描哪些内容
-->
<context:component-scan base-package="com.atguigu" use-defaultfilters="false">
 <context:include-filter type="annotation" 
 expression="org.springframework.stereotype.Controller"/><!--代表只扫描Controller注解的类-->
</context:component-scan>

<!--示例 2
 下面配置扫描包所有内容
 context:exclude-filter: 设置哪些内容不进行扫描
-->
<context:component-scan base-package="com.atguigu">
 <context:exclude-filter type="annotation" 
 expression="org.springframework.stereotype.Controller"/><!--表示Controller注解的类之外一切都进行扫描-->
</context:component-scan>

2. Inject attributes based on annotations


First create a demo demo:
insert image description here

1. First create a UserDao interface and its implementation class UserDaoimpl_1 and create an object

//1.UserDao接口
public interface UserDao {
    
    
    public void add();
}
//2.UserDao接口实现类 UserDaoimpl_1   

@Component
public class UserDaoimpl_1 implements UserDao{
    
    
    public void add(){
    
    
        System.out.println("第一个实现类");
    }
}

2. Create the UserService class and create its object

//3.创建UserService类
import org.springframework.stereotype.Component;

@Component
public class UserService {
    
    
   
    public void test(){
    
    
        System.out.println("Userservice.......");
        dao.add();
    }
}

3. Write the Spring configuration file (code omitted)...


(1) @Autowired: According toattribute typeinject property

import org.springframework.stereotype.Component;

@Component
public class UserService {
    
    

    //通过@Autowired添加一个UserDao类型的属性
    //不需要添加set方法
    
    @Autowired
    private UserDao dao;

    public void test(){
    
    
        System.out.println("Userservice.......");
        dao.add();
    }
}

Running results, it can be seen that the imported attribute is the object of the first implementation class
insert image description here

(2) @Qualifier: Injection based on name

When our UserDao interface has two implementation classes, if we still only use the @Autowired annotation, 系统会不知道该引入哪一个实现类而报错so we need to use the @Qualifier annotation to inject properties through the name of the class

@Qualifier 注解要和和上面@Autowired 一起使用

In the first step, we create another UserDao implementation class UserDaoimpl_2

@Component
public class UserDaoimpl_2 implements UserDao{
    
    
    public void add(){
    
    
        System.out.println("第二个实现类");
    }
}

(At this time, the demo structure is as follows)
insert image description here

The second step is to re-introduce attributes in UserService

@Component
public class UserService {
    
    
    //添加一个UserDao类型的属性
    //不需要添加set方法
    //然后在属性上面添加注解
    //注意:value的值必须为被引入类的“对象名”
    
    @Autowired
    @Qualifier(value = "userDaoimpl_2")
    private UserDao dao;

    public void test(){
    
    
        System.out.println("Userservice.......");
        dao.add();
    }
}

As a result of the operation, it can be seen that the introduced attribute is an object of the second implementation class
insert image description here
(3) @Resource: it can be injected according to type or name

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

(4) @Value: Inject common type properties

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

3. Fully annotated development (No Spring configuration files are required, all use annotations)

(1) Create a configuration class to replace the xml configuration file

//1.设置该类作为配置类,替代 xml 配置文件
@Configuration 
//2.开启组件扫描(此处demo3为包名)
@ComponentScan(basePackages = "demo3") 
public class SpringConfig {
    
    
}

(2) Write test classes

public class testDemo {
    
    
    public static void main(String[] args) {
    
    
        //1. 加载配置类,此时选择AnnotationConfigApplicationContext()实现类
        //参数为配置类的类名 注意!!!参数不要加引号!!!
        ApplicationContext context =
                new AnnotationConfigApplicationContext(SpringConfig.class);

        UserService userService = context.getBean("userService",UserService.class);
        userService.test();
    }
}

Notice: When using the configuration class, the context object is obtained through "AnnotationConfigApplicationContext()", and
the parameter is "configuration class name.class"
(absolutely do not add double quotes to the parameter!!! An error will be reported)

Guess you like

Origin blog.csdn.net/qq_47354826/article/details/120537253