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

    BaseService<T>:有RoleService和UserService两的子类

    BaseRepepositry<T>:有UserRepository和RoleRepositry两个子类

    由于BaseService<T>和BaseRepepositry<T>有关系所以,得出下面的子类也存在这样的关系

    具体代码

    1、User.java

    1 package com.proc.bean;
    2 
    3 public class User {
    4 
    5 }

    2、BaseRepository.java

    1 package com.proc.repository;
    2 
    3 public class BaseRepository<T> {
    4 
    5 }

    3、BaseService.java

     1 package com.proc.service;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 
     5 import com.proc.repository.BaseRepository;
     6 
     7 public class BaseService<T> {
     8 
     9     @Autowired
    10     protected BaseRepository<T> baseRepository;
    11     
    12     public void save(){
    13         System.out.println("save ………………");
    14         System.out.println(baseRepository);
    15     }
    16 }

    4、UserRepository.java

     1 package com.proc.repository;
     2 
     3 import org.springframework.stereotype.Repository;
     4 
     5 import com.proc.bean.User;
     6 
     7 @Repository
     8 public class UserRepository extends BaseRepository<User> {
     9 
    10 }

    5、UserService.java

     1 package com.proc.service;
     2 
     3 import org.springframework.stereotype.Service;
     4 
     5 import com.proc.bean.User;
     6 
     7 @Service
     8 public class UserService extends BaseService<User>{
     9     
    10 }

    6、xml配置

    <context:component-scan base-package="com.proc" />

    7、代码测试

    1 ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
    2 UserService userService=(UserService) ctx.getBean("userService");
    3 userService.save();

    输出结果:

    save ………………
    com.proc.repository.UserRepository@15bfd87

    这里可以看到对象的类型为UserRepository

  • 相关阅读:
    1.MySql安装
    struts文件上传、文件下载
    Java内存模型
    虚拟机类加载机制
    JAVA内存管理
    算法
    POI
    SSH项目(1)
    classpath路径和properties
    AngularJS路由实现单页面跳转
  • 原文地址:https://www.cnblogs.com/caoyc/p/5626484.html
Copyright © 2011-2022 走看看