<!-- 实验23:测试泛型依赖注入★ -->
Book.java
package com.atguigu.bean;
public class Book {
}
User.java
package com.atguigu.bean;
public class User {
}
BaseDao.java
package com.atguigu.dao;
/**
* 定义了基本的增删改查方法
*/
public abstract class BaseDao<T> {
public abstract void save();
}
BookDao.java
package com.atguigu.dao;
import org.springframework.stereotype.Repository;
import com.atguigu.bean.Book;
@Repository
public class BookDao extends BaseDao<Book>{
@Override
public void save() {
// TODO Auto-generated method stub
System.out.println("BookDao....保存图书。。。");
}
}
UserDao.java
package com.atguigu.dao;
import org.springframework.stereotype.Repository;
import com.atguigu.bean.User;
@Repository
public class UserDao extends BaseDao<User>{
@Override
public void save() {
// TODO Auto-generated method stub
System.out.println("UserDao...保存用户....");
}
}
BaseService.java
package com.atguigu.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.atguigu.dao.BaseDao;
public class BaseService<T> {
@Autowired
private BaseDao<T> baseDao;
public void save(){
System.out.println("自动注入的dao:"+baseDao);
baseDao.save();
}
}
BookService.java
package com.atguigu.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.atguigu.bean.Book;
import com.atguigu.dao.BaseDao;
import com.atguigu.dao.BookDao;
@Service
public class BookService extends BaseService<Book>{
}
UserService.java
package com.atguigu.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.atguigu.bean.User;
import com.atguigu.dao.UserDao;
@Service
public class UserService extends BaseService<User>{
}
IOCTest.java
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;
public class IOCTest {
@Test
public void test() {
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService = ioc.getBean(BookService.class);
UserService userService = ioc.getBean(UserService.class);
bookService.save();
userService.save();
//父类的类型:com.atguigu.service.BaseService
//带泛型的父类类型:com.atguigu.service.BaseService<com.atguigu.bean.Book>
//Spring中可以使用带泛型的父类类型来确定这个子类的类型
System.out.println(bookService.getClass().getGenericSuperclass());
}
}