泛型依赖注入

来源:互联网 发布:ubuntu 添加路由 编辑:程序博客网 时间:2024/06/07 21:19

以下类都在包com.po中

实体类:

User

第一层:

BaseRepository<T> BaseService<T>

BaseService<T>里的成员变量指向了BaseRepository<T>,要为其添加@Autowired注解

第二层:

UserRepository UserService

他们两个继承对应的父类,要分别为各自添加@Repository注解和@Service注解

public class User {}
public class BaseRepository<T> {}
public class BaseService<T> {@Autowiredprotected BaseRepository<T> repository;public void out(){System.out.println(repository);}}
@Repositorypublic class UserRepository extends BaseRepository<User>{}
@Servicepublic class UserService extends BaseService<User>{}

主方法中调用:

public class Main {public static void main(String[] args) {ApplicationContext ctx=new ClassPathXmlApplicationContext("test.xml");UserService us=(UserService) ctx.getBean("userService");us.out();}}
配置文件test.xml主要内容
<context:component-scan base-package="com.po"></context:component-scan>
①在类上有了注解;②在xml文件中扫描了该类;就可以通过类名首字母小写来getBean