spring4新特性-泛型依赖注入

本文介绍了一种基于Java的分层设计模式,通过抽象类Repository与Service定义公共方法,并在具体的实现类UserRepository和UserService中完成特定业务逻辑的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值