spring泛型依赖注入
发布日期:2021-05-07 09:14:20 浏览次数:20 分类:精选文章

本文共 2807 字,大约阅读时间需要 9 分钟。

泛型依赖注入

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QlRvZODG-1620216626229)(E:\开发笔记\ssm\spring\images\ioc\泛型依赖注入.jpg)]

  1. bean层

    package com.atguigu.bean;public class Book {     }
    package com.atguigu.bean;public class User {     }
  2. dao层

    package com.atguigu.dao;import org.springframework.stereotype.Repository;/** * 定义了各种 增删改查方法 * * @param 
    */@Repositorypublic abstract class BaseDao
    { public abstract void save(); }
    package com.atguigu.dao;import org.springframework.stereotype.Repository;import com.atguigu.bean.Book;@Repositorypublic class BookDao extends BaseDao
    { @Override public void save() { System.out.println("保存图书"); } }
    package com.atguigu.dao;import org.springframework.stereotype.Repository;import com.atguigu.bean.User;@Repositorypublic class UserDao extends BaseDao
    { @Override public void save() { System.out.println("保存用户"); }}
  3. service层

    //子类继承了父类,就相当于子类拥有了父类的属性与方法,尽管父类没有创建bean对象,但是因为子类创建了bean对象,所以在注入属性时会根据子类的的泛型注入属性。package com.atguigu.service;import org.springframework.beans.factory.annotation.Autowired;import com.atguigu.dao.BaseDao;public class BaseService
    { @Autowired BaseDao
    baseDao; public void save(){ System.out.println("自动注入"+baseDao); baseDao.save(); } }
    package com.atguigu.service;import org.springframework.stereotype.Service;import com.atguigu.bean.Book;@Servicepublic class BookService extends BaseService
    { }
    package com.atguigu.service;import org.springframework.stereotype.Service;import com.atguigu.bean.User;@Servicepublic class UserService extends BaseService
    { }
  4. 测试

    package com.atguigu.test;import static org.junit.Assert.*;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.atguigu.service.BookService;import com.atguigu.service.UserService;import com.sun.xml.internal.bind.CycleRecoverable.Context;public class IOCTest {     	ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");		@Test	public void test() {     		BookService bookService = context.getBean("bookService",BookService.class);		UserService userService = context.getBean("userService",UserService.class);				bookService.save();		userService.save();        /*        	自动注入com.atguigu.dao.BookDao@76329302            保存图书            自动注入com.atguigu.dao.UserDao@5e25a92e            保存用户        */		//		Spring中可以使用带泛型的父类类型来确定子类类型		System.out.println(bookService.getClass().getGenericSuperclass());//		com.atguigu.service.BaseService
    }}
    System.out.println(bookService.getClass().getGenericSuperclass());

    // com.atguigu.service.BaseService<com.atguigu.bean.Book>

    }

    }

     
上一篇:Python(八)之操作MySQL
下一篇:spring单元测试

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年04月08日 04时59分55秒