Spring 泛型依赖注入,是利用泛型的优点对代码时行精简,将可重复使用的代码全部放到一个类之中,方便以后的维护和修改,同时在不增加代码的情况下增加代码的复用性。
示例代码:
- 创建实体类
Product
Userpackage test.spring.model;public class Product {private int id ;private String name;/* setter getter省略 */@Overridepublic String toString() {return "Product [id=" + id + ", name=" + name + "]";}}
package test.spring.model;public class User {private int id;private String name;/* setter、getter省略 */@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + "]";}public User() {super();}}
- 创建Dao层相关接口及实现类
对dao层的相同功能提取出来,创建一个带泛型的BaseDao类用于共用。package test.spring.Dao;import org.springframework.stereotype.Repository;/*必须加入注解,将BaseDao注入Spring容器,因为BaseService中有引用该类*/ @Repository public class BaseDao<T> {public void add(T t) {System.out.println("BaseDao...."+t);}}
UserDao接口package test.spring.Dao;import test.spring.model.User;public interface UserDao {public void add(User user);}
UserDao实现类
package test.spring.Dao; import org.springframework.stereotype.Repository;import test.spring.model.User; @Repository ("userDaoImpl") public class UserDaoImpl extends BaseDao<User> implements UserDao {}
ProductDao接口
package test.spring.Dao;import test.spring.model.Product;public interface ProductDao {public void add(Product pro); }
ProductDao实现类
package test.spring.Dao;import org.springframework.stereotype.Repository;import test.spring.model.Product; @Repository("productDao") public class ProductDaoImpl extends BaseDao<Product> implements ProductDao {}
- Spring配置
<?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"><context:component-scan base-package="test.spring" > </context:component-scan></beans>
- 测试
结果:package testSpring;import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import test.spring.model.Product; import test.spring.model.User; import test.spring.service.ProductService; import test.spring.service.UserService;public class TestSpring {@Testpublic void testUser() {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");UserService userService=(UserService) ac.getBean("userService");userService.add(new User());System.out.println("-----------------------------");ProductService proService= (ProductService) ac.getBean("prodcutService");proService.add(new Product());} }