zoukankan      html  css  js  c++  java
  • Spring初学之泛型依赖注入

    主要讲泛型依赖注入,所以核心在java文件,配置文件中只需配置扫描包即可,如下:

    <?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-4.3.xsd">
    
    <context:component-scan base-package="spring.beans.generic.di"></context:component-scan>
    
    </beans>
    spring.beans.generic.di包中有两个配置的泛型的父类,有两个继承这两个父类的子类,还有一个实体bean,先看实体bean:
    由于只是模拟一下,没必要写属性,创建一个类即可。
    package spring.beans.generic.di;
    
    public class User {
    
    }

    再看两个泛型的父类:

    package spring.beans.generic.di;
    
    public class BaseRepository<T> {
    
    }
    package spring.beans.generic.di;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    public class BaseService<T> {
        @Autowired
        protected BaseRepository<T> repository;
        public void add(){
            System.out.println("add...");
            System.out.println(repository);
        }
    }

    子类:

    package spring.beans.generic.di;
    
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class UserRepository extends BaseRepository<User>{
    
    }
    package spring.beans.generic.di;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserService extends BaseService<User> {
    
    
    }

    测试:

    package spring.beans.generic.di.test;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import spring.beans.generic.di.UserService;
    
    public class Main {
    
        public static void main(String[] args) {
    
            ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-generic-di.xml");
            UserService userService=(UserService) ctx.getBean("userService");
            userService.add();//输出的是子类的对象
        }
    
    }

    输出:

    add...
    spring.beans.generic.di.UserRepository@8646db9
  • 相关阅读:
    MySQL数据同步,出现Slave_SQL_Running:no和slave_io_running:no问题的解决方法
    【坑】解决CentOS 7.1版本以上安装好zabbix 3.4 无法重启zabbix-server的问题
    unison+inotify的Web目录同步方案
    vue-cli3.0配置图片转base64的规则
    nginx将http升级到https并且同时支持http和https两种请求、http自动转向https
    linux中使用ps -ef
    form表单input回车提交问题
    Linux创建Jenkins启动脚本以及开机启动服务
    xshell破解
    WebSocket断开原因、心跳机制防止自动断开连接
  • 原文地址:https://www.cnblogs.com/hyyq/p/6701831.html
Copyright © 2011-2022 走看看