Spring: Generic Dependency Injection

insert image description here

Generic Dependency Injection

Generics : classes, structures, interfaces, and methods with placeholders (type parameters), define a formal parameter by means of <>, and specify the specific type when instantiating

Dependency injection : the specific implementation of IoC, which refers to the way in which the dependencies between objects are dynamically injected by the external container when the program is running.

Generic dependency injection : While performing dependency injection, using generics to extract reusable code in the same place can simplify code, improve code reusability, and facilitate maintenance and modification

Simple example:
first create two entity classes, student and teacher, and define two attributes: number and name:

package cn.edu.springdemo.model;

//学生类
public class Student {
    
    
    private int id ; //学号
    private String name ; //姓名

    public Student() {
    
    
        super();
    }

    public int getId() {
    
    
        return id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
package cn.edu.springdemo.model;

//教师类
public class Teacher {
    
    
    private int id; //职工号
    private String name; //姓名

    public Teacher() {
    
    
        super();
    }

    public int getId() {
    
    
        return id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    @Override
    public String toString() {
    
    
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

Then define an interface StudentDao and declare an Update method:

package cn.edu.springdemo.dao;

import cn.edu.springdemo.model.Student;

public interface StudentDao {
    
    
    public void Update(Student student);
}

Define an interface TeacherDao and also declare an Update method:

package cn.edu.springdemo.dao;

import cn.edu.springdemo.model.Teacher;

public interface TeacherDao {
    
    
    public void Update(Teacher teacher);
}

Both interfaces have Update method which can be extracted in the same place. That is, define a generic GenericsDao, and implement code reuse through type parameters to improve code writing efficiency:

package cn.edu.springdemo.dao;

//泛型
public class GenericsDao<T> {
    
    
	//定义形式参数,调用时再具体指明
    public void Update(T t){
    
    
        System.out.println(t);
    }
}

Then create the implementation class of the corresponding interface, and inherit the generic GenericsDao and pass in the corresponding type:

package cn.edu.springdemo.dao;

import cn.edu.springdemo.model.Student;
import org.springframework.stereotype.Repository;

//通过注解方式配置 bean 示例
@Repository("studentDao")
public class StudentDaoImpl extends GenericsDao<Student> implements StudentDao {
    
    
    // Update 方法无需再写
}
package cn.edu.springdemo.dao;

import cn.edu.springdemo.model.Teacher;
import org.springframework.stereotype.Repository;

@Repository("teacherDao")
public class TeacherDaoImpl extends GenericsDao<Teacher> implements TeacherDao {
    
    
    //同样 Update 方法无需再写
}

Similarly, extract the reusable injection code in the generic GenericsService in the Service layer:

package cn.edu.springdemo.service;

import cn.edu.springdemo.dao.GenericsDao;
import org.springframework.beans.factory.annotation.Autowired;

public class GenericsService<T> {
    
    
    @Autowired
    protected GenericsDao<T> genericsDao; //泛型注入
}

Then define the StudentService and TeacherService interfaces, and declare an Update method;
then let the implementation class inherit the generic GenericsService, and call the genericsDao property:

package cn.edu.springdemo.service;

import cn.edu.springdemo.model.Student;
import org.springframework.stereotype.Service;

@Service("studentService")
public class StudentServiceImpl extends GenericsService<Student> implements StudentService {
    
    
    @Override
    public void Update(Student student) {
    
    
        genericsDao.Update(student);
    }
}
package cn.edu.springdemo.service;

import cn.edu.springdemo.model.Teacher;
import org.springframework.stereotype.Service;

@Service("teacherService")
public class TeacherServiceImpl extends GenericsService<Teacher> implements TeacherService {
    
    
    public void Update(Teacher teacher){
    
    
        genericsDao.Update(teacher);
    }
}

Final test result:

package cn.edu.springdemo.test;

import cn.edu.springdemo.service.StudentService;
import cn.edu.springdemo.service.TeacherService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AdminTest {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("annontationDemo.xml");
        
        StudentService studentService = (StudentService) applicationContext.getBean("studentService");
        System.out.println(studentService);

        TeacherService teacherService = (TeacherService) applicationContext.getBean("teacherService");
        System.out.println(teacherService);
    }
}

The result is shown in the figure:
insert image description here

problem solved

Error: Could not autowire. No beans of 'GenericsDao' type found. more... (Ctrl+F1)
Solution: In fact, there is no error, and it has no effect on the running result. But it doesn't look very comfortable, the solution only needs to lower the error level

insert image description here

Steps: Click File, click Settings..., select Editor in the pop-up window, then click Inspections, find Spring, select Spring Core and Code, click Autowiring for Bean Class, and finally under Severity on the right, reduce the Error level to Warning. As shown in the picture:
insert image description here

Problem solved successfully. As shown in the picture:
insert image description here

Guess you like

Origin blog.csdn.net/qq_56886142/article/details/130745451