【Spring4.0新特性】——泛型依赖注入
前言Spring4.0加入了泛型依赖注入,为子类注入了子类对应的泛型类型的成员变量的引用,泛型依赖注入就是允许我们在使用spring进行依赖注入的同时,利用泛型的优点对代码进行精简,将可重复使用的代码全部放到一个类之中,方便以后的维护和修改。同时在不增加代码的情况下增加代码的复用性!以下我们用一个简单的例子讲解一下泛型依赖,以及在这个过程可能遇到的问题! 内容实例的结构目录: <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.xsd ">
<context:component-scan base-package="com.cyl.spring.beans.generic.di"></context:component-scan>
</beans>
代码: public class BaseService<T> {
@Autowired
protected BaseRepository<T> repository;
public void add(){
System.out.println("add.....");
System.out.println(repository);
}
}
BaseRepository: public class BaseRepository<T> {
}
RoleService和UserService分别继承BaseService,而RoleRepository和UserRepository分别继承于BaseRepository //UserService
@Service
public class UserService extends BaseService<User> {
}
//RoleService
@Service
public class RoleService extends BaseService<Role>{
}
//UserRepository
@Repository
public class UserRepository extends BaseRepository<User> {
}
//RoleRepository
@Repository
public class RoleRepository extends BaseRepository<Role> {
}
Main类检测他们之间的关系: public class Main {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-generic-di.xml");
UserService userService=(UserService) ctx.getBean("userService");
RoleService roleService=(RoleService) ctx.getBean("roleService");
userService.add();
roleService.add();
}
}
结果输出了: add.....
com.cyl.spring.beans.generic.di.UserRepository@71d15f18
add.....
com.cyl.spring.beans.generic.di.RoleRepository@17695df3
最终泛型类之间的关系用一张图来表示: 但是在这里我们要注意一个问题: //RoleService主要是这里的泛型接口的实体仍然是User的情况下,
//代码输出的结果就不一样了:
@Service
public class RoleService extends BaseService<User>{
}
add.....
com.cyl.spring.beans.generic.di.UserRepository@71d15f18
add.....
com.cyl.spring.beans.generic.di.UserRepository@17695df3
因为写成了 //UserRepository
@Repository
public class UserRepository extends BaseRepository<User> {
}
//RoleRepository
@Repository
public class RoleRepository extends BaseRepository<User> {
}
控制台会输出错误信息:以为目前UserRepository 和RoleRepository 都满足继承 总结泛型赖注入并不仅限于在持久层使用。我们也可以在持久层使用泛型依赖注入的基础上,在业务层等其他地方也使用泛型依赖注入! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |