Spring-02 about bean scope, life cycle, annotation-based injection, instance generation, semi-automatic annotation assembly and automatic annotation

Spring-02

1.bean scope

There are 7 bean scopes, the most commonly used are singleton and prototype
Insert picture description here

1.1 singleton singleton

Singleton is the default scope of the Spring container. When the scope of Bean is singleton, there will only be one shared Bean instance in the Spring container. Singleton scope is the most ideal choice for beans without session state (such as Dao components, Service components).

 singleton 1.在容器启动只创建一个 id 为student1 bean  2.并且放置在容器中,容器管理他的生命周期
<!--
       声明让容器创建一个 Student类型的bean  id student1
      scope="singleton"  容器创建bean scope 默认的 作用域是单例singleton
      singleton 1.在容器启动只创建一个 id 为student1的 bean  2.并且放置在容器中,容器管理他的生命周期
-->
<bean class="com.yth.entity.Student" id="student1" scope="singleton">
    <property name="id" value="100"></property>
    <property name="name" value="赵四"></property>
</bean>

test

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scope/student.xml");
//关于singleton 单例的测试
@Test
public void Test01(){
    
    
    Student student = (Student) applicationContext.getBean("student1");
    System.out.println(student);
}

1.2 Prototype of propertype

When the user obtains the bean from the container, the container is created. The container is only responsible for creating it, not for preserving and maintaining its life cycle

<!--
    声明让容器创建bean 作用域prototype
    prototype   1.用户向容器获取时 创建id student2对象 2.每次都创建新的对象
                3.容器只负责帮我们创建 不会放置在容器中,不会管理bean 的生命周期 ,由用户自己负责
-->
<bean class="com.yth.entity.Student" id="student2" scope="prototype">
    <property name="id" value="101"></property>
    <property name="name" value="广坤"></property>
</bean>

test

//关于propertype 原型的测试
@Test
public void Test02(){
    
    
    Student student1 = (Student) applicationContext.getBean("student2");
    System.out.println(student1.hashCode());
    Student student2 = (Student) applicationContext.getBean("student2");
    System.out.println(student2.hashCode());
}

2. Bean's life cycle

Bean's birth, old age, sickness and death

Singleton bean: as the container starts, the bean is created, and the container is responsible for maintaining the life cycle of the bean

Prototype bean: The bean is not created when the container starts, and the bean is created by the container when the user obtains it. Each time it is a new bean, the container department manages its life cycle

The Spring container can manage the life cycle of Bean part of the scope. The description is as follows

  • singleton

The Spring container can manage the life cycle of a bean in the singleton scope. In this scope, Spring can accurately know when the bean is created, when it is initialized, and when it is destroyed.

  • prototype

Spring is only responsible for the creation of Beans in the prototype scope. When the container creates a Bean instance, the Bean instance is handed over to the client code for management, and the Spring container will no longer track its life cycle.

Example:

1. Add methods related to life cycle in Student

 /**
     * 初始化方法
     */
    public void  init(){

        System.out.println("对象初始化");
    }

    /**
     * 销毁方法
     */
    public void destroy(){
        System.out.println("对象销毁了");
    }

2. Create lifebean.xml, set the corresponding method

<!--
        init-method="init"  容器创建bean 时调用 初始化方法
        destroy-method="destroy"  当容器销毁时调用 销毁方法
       -->
    <bean class="com.yth.entity.Student" id="student1" scope="singleton"
          init-method="init" destroy-method="destroy">
        <property name="id" value="104"></property>
        <property name="name" value="赵四"></property>
    </bean>
    <!--
        声明 一个原型的bean  当用户获取时创建,容器只负责创建 不负责bean 的生命周期,由用户自己管理
        当容器销毁时 bean 的destroy 不会被容器调用
    -->
    <bean  id="student2" class="com.yth.entity.Student"
           scope="prototype" init-method="init" destroy-method="destroy">   
        <property name="id" value="105"></property>
        <property name="name" value="广坤"></property>
    </bean>

3. Test

//关于bean的生命周期
@Test
public void Test03(){
    
    
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("life\\lifeBean.xml");
    // 向容器获取原型  对象此时 触发原型的创建
    Student student1 = (Student) applicationContext.getBean("student1");
    // 显示调用容器的销毁方法  销毁前会将容器中所有的bean 先销毁, 调用bean 的destroy()
    Student student2 = (Student) applicationContext.getBean("student2");
    applicationContext.destroy();
}

3. Annotation-based assembly

XML-based assembly may cause the XML configuration file to be too bloated and bring certain difficulties to subsequent maintenance and upgrades. To this end, Spring provides comprehensive support for Annotation (annotation) technology.

3.1 Injected annotations

@Autowired : Used to annotate Bean property variables, property setter methods and construction methods, and cooperate with the corresponding annotation processor to complete the automatic configuration of the Bean.

@Qualifier : Used in conjunction with the @Autowired annotation, the default assembly by Bean type will be modified to assembly by the instance name of the Bean. The instance name of the Bean is specified by the parameter of the @Qualifier annotation.

@Resource : Its role is the same as Autowired. There are two important attributes in @Resource: name and type. Spring resolves the name attribute to the Bean instance name and the type attribute to the Bean instance type.

//    @Autowired  // 根据类型进行注入若有,多个类型的实例,需要配合   @Qualifier("studentDaoImpl2")
//    @Qualifier("studentDaoImpl2")

    @Resource()  // 默认按照注解的字段名称进行装配,  若没有找到根据类型装配,如果对应类型的实例有多个需要限定
    private StudentDao studentDao ;

3.2 Annotation of the generated instance

@Component: Used to describe the Bean in Spring. It is a generalized concept and only represents a component.

@Repository: Used to identify the data access layer (DAO) class as a Bean in Spring. dao object, can access the database

@Service: Used to identify the class of the business layer (Service) as a Bean in Spring. The service object can do business processing and have functions such as affairs

@Controller: Used to identify the class of the control layer (Controller) as a Bean in Spring. The controller object can accept the parameters submitted by the user and display the processing result of the request.

3.3 Semi-automatic annotation assembly

Can only be injected to make the injected annotations take effect. The generation of beans also needs to be configured in xml

The implementation is context:annotation-config</context:annotation-config>

1. First declare the bean in the container

2. Use the corresponding injection annotation to inject the bean

3. The injected annotation takes effect

<!--
        作用就是让 注入的注解生效
    -->
<context:annotation-config></context:annotation-config>

<!--1. 声明 bean-->
<bean id="studentDao1" class="com.yth.dao.impl.StudentDaoImpl"></bean>
<bean id="studentDao2" class="com.yth.dao.impl.StudentDaoImpl"></bean>

<bean id="studentService" class="com.yth.service.impl.StudentServiceImpl">
</bean>
public class StudentServiceImpl implements StudentService {
    
    
    //注入注解 注入bean
    @Autowired         //去容器中 查找bean,并设置到当前属性中  如果容器有 多个类型的bean则报错
 //  @Qualifier("studentDao1")//  @Qualifier 与@Autowired 配合 ,当根据类型找到多个时 使用  @Qualifier 按照id  或者name 查找为一个bean
  //  @Resource(name = "studentDao")// 首先按照 id 为属性名studentDao1 去容器中找到对应的bean 2.如果找不到 在按照类型去查找 如果找到多个 报错
    private StudentDao studentDao;
    public StudentDao getStudentDao() {
    
    
        return studentDao;
    }
    public void setStudentDao(StudentDao studentDao) {
    
    
        this.studentDao = studentDao;
    }
    public Student findStudentById(int id) {
    
    
        return studentDao.fingStudentById(id);
    }
}
  <!--
        作用就是让 注入的注解生效
    -->
    <context:annotation-config></context:annotation-config>

test

public class Test02 {
    
    
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("annotation\\ annotation.xml");
    //关于半自动注解装配测试
    @Test
    public void Test01(){
    
    
        StudentService studentService = applicationContext.getBean(StudentService.class);
        Student studentById = studentService.findStudentById(102);
        System.out.println(studentById);
    }
    //增加studentDao 的bean的声明,id不同的测试,再添加一个注解@Qualifier("studentDao1"),获取id为studentDao1的bean
    @Test
    public void Test02(){
    
    
      //  StudentService studentService = applicationContext.getBean(StudentService.class);
        StudentService studentService = (StudentService) applicationContext.getBean("studentService");
        Student studentById = studentService.findStudentById(102);
        System.out.println(studentById);
    }
    //@Resource(name = "studentDao1")  使用resource注解
    @Test
    public void Test03(){
    
    
        StudentService studentService = (StudentService) applicationContext.getBean("studentService");
        Student studentById = studentService.findStudentById(102);
        System.out.println(studentById);
    }
}

3.4 Automatic annotation

context:component-scan

Automatic annotation is the automatic generation of beans through annotations and assembly

Implementation: Declare context:component-scan in the xml to make the injected annotations (@Autowired @Qualifie @Resource) generated bean annotations (@Component@Repository @Service @Controller) take effect under the corresponding package

achieve

1. Turn on automatic annotation xml

	<!--
        开启 自动注解功能 使 注入的注解(@Autowired @Qualifie @Resource )生成bean的注解(@Component@Repository @Service @Controller)生效
    -->
     <context:component-scan base-package="com.qfedu"></context:component-scan>

2. Mark the need to generate the bean and the main injected properties

dao

@Repository // 标记当前类是dao层
public class StudentDaoImpl implements StudentDao {
    
    
    public Student fingStudentById(int id) {
    
    
        Student student =new Student();
        student.setId(102);
        student.setName("刘能");
        return student;
    }
}

service

@Service
public class StudentServiceImpl implements StudentService {
    
    
    //注入注解 注入bean
    @Autowired         //去容器中 查找bean,并设置到当前属性中  如果容器有 多个类型的bean则报错
 //  @Qualifier("studentDao1")//  @Qualifier 与@Autowired 配合 ,当根据类型找到多个时 使用  @Qualifier 按照id  或者name 查找为一个bean
  //  @Resource(name = "studentDao")// 首先按照 id 为属性名studentDao1 去容器中找到对应的bean 2.如果找不到 在按照类型去查找 如果找到多个 报错
    private StudentDao studentDao;

    public StudentDao getStudentDao() {
    
    
        return studentDao;
    }
    public void setStudentDao(StudentDao studentDao) {
    
    
        this.studentDao = studentDao;
    }
    public Student findStudentById(int id) {
    
    
        return studentDao.fingStudentById(id);
    }
}

test

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("autoAnnotation\\autoAnnotation.xml");

    //全自动注解的测试
    @Test
    public void Test01(){
    
    
        StudentService studentService = (StudentService) applicationContext.getBean(StudentService.class);
        Student studentById = studentService.findStudentById(102);
        System.out.println(studentById);
    }

Guess you like

Origin blog.csdn.net/qq_41520945/article/details/109189839