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
  • 相关阅读:
    echart所有汉字都显示中文,就echarts的toolbox注释显示乱码
    【转】 JSONObject使用方法
    JSON: property "xxx" has no getter method in class "..."
    【转】Oracle数据库中Sequence的用法
    Android实例-获取程序版本号(XE10+小米2)
    Android实例-调用系统APP(XE10+小米2)
    BAT-使用BAT方法清理系统垃圾
    Android实例-全屏显示程序(XE10+小米2)(无图)
    问题-Delphi2007编译时提示内存错误“sxs.dll. No Debug Info.ACCESS 0xXXXXX"
    DelphiXE7中创建WebService(服务端+客户端)
  • 原文地址:https://www.cnblogs.com/hyyq/p/6701831.html
Copyright © 2011-2022 走看看