spring4新特性-泛型依赖注入

1 文件结构 

2 具体类

 2.1两个抽象类,在Service里面写公共的方法,在各自的具体实现类里面写各自的方法

package repo;

import model.User;

/**
* Created by pinker on 2016/10/30.
*/
public abstract class Repository<T> {
public abstract T getAllUser() throws Exception;
}

package service;

import model.User;
import org.springframework.beans.factory.annotation.Autowired;
import repo.Repository;

/**
* Created by pinker on 2016/10/30.
*/
public abstract class Service<T>{
@Autowired
private Repository<T> repository;

public abstract T getAllUser() throws Exception;

public void save()throws Exception{
System.out.println("Service----------->"+repository);
}
}
2.2 实现类
package repoimpl;

import model.User;
import repo.Repository;
/**
* Created by pinker on 2016/10/30.
*/
@org.springframework.stereotype.Repository
public class UserRepository extends Repository<User> {
@Override
public User getAllUser() throws Exception {
User user = new User(1, "HS", 23);
return user;
}
}
package serviceimpl;

import model.User;
import org.springframework.beans.factory.annotation.Autowired;
import repoimpl.UserRepository;
import service.Service;

/**
* Created by pinker on 2016/10/30.
*/
@org.springframework.stereotype.Service
public class UserService extends Service<User> {
@Autowired
private UserRepository userRepository;

@Override
public User getAllUser() throws Exception {
return userRepository.getAllUser();
}
}
2.3 测试类(偷懒了,因为只用了两个包,不是测试的写法)
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import serviceimpl.UserService;

/**
* Created by pinker on 2016/10/30.
*/


public class test {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/Spring.xml");
UserService userService = (UserService) context.getBean("userService");
userService.save();
System.out.println(userService.getAllUser());
}
}
2.4 结果


可以看出,里面既可以调用公共方法也可以调用自己特有的实现类及自己的方法
 
 
原文地址:https://www.cnblogs.com/xd03122049/p/6013857.html