在传统居民用电管理中,人工抄表、手工计费的方式存在效率低下、数据易错、对账困难等诸多痛点。针对这些问题,本文介绍一款基于SpringBoot的企业级智能电费管理平台,该系统通过数字化手段实现了从用电数据采集、费用计算到账单生成的全流程自动化管理。
系统架构与技术栈
该平台采用典型的三层架构设计,技术选型注重成熟度和开发效率。后端基于SpringBoot 2.x框架,极大简化了传统Spring应用的配置和部署流程。控制层使用Spring MVC处理HTTP请求,返回统一的JSON数据格式;业务逻辑层封装了复杂的电费计算规则,支持阶梯电价、分时电价等多种计费模式;数据访问层采用Spring Data JPA实现与MySQL数据库的交互。
前端技术栈包含HTML5、CSS3和JavaScript,结合Thymeleaf模板引擎实现页面渲染。项目使用Maven进行依赖管理,配置文件采用YAML格式,提高了配置的可读性和维护性。
# 应用配置文件示例
spring:
datasource:
url: jdbc:mysql://www.csbishe.cn/ssm_juminydjf?useSSL=false&serverTimezone=Asia/Shanghai
username: ssm_juminydjf
password: ssm_juminydjf
driver-class-name: com.mysql.cj.jdbc.Driver
dbcp2:
max-wait-millis: 10000
min-idle: 5
initial-size: 5
jpa:
show-sql: true
mvc:
view:
prefix: /WEB-INF/page/
suffix: .html
server:
port: 8080
servlet:
session:
timeout: -1
数据库设计深度解析
用户权限管理体系
系统设计了完善的RBAC(基于角色的访问控制)模型,通过sys_user、sys_role_menu、sys_user_role三张核心表实现灵活的权限控制。
-- 系统用户表结构
CREATE TABLE `sys_user` (
`user_id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL COMMENT '用户名',
`password` varchar(100) DEFAULT NULL COMMENT '密码',
`email` varchar(100) DEFAULT NULL COMMENT '邮箱',
`mobile` varchar(100) DEFAULT NULL COMMENT '手机号',
`status` tinyint(4) DEFAULT NULL COMMENT '状态 0:禁用 1:正常',
`create_user_id` bigint(20) DEFAULT NULL COMMENT '创建者ID',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`type` varchar(255) DEFAULT NULL COMMENT '用户类型',
PRIMARY KEY (`user_id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COMMENT='系统用户'
该表设计具有以下技术亮点:
- 使用
bigint(20)作为主键,确保大规模用户数据下的唯一性 username字段设置唯一索引,避免用户名重复status字段采用tinyint类型,仅需1字节存储空间,优化存储效率create_time字段记录用户创建时间,便于审计和追踪
-- 角色菜单关系表
CREATE TABLE `sys_role_menu` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`role_id` bigint(20) DEFAULT NULL COMMENT '角色ID',
`menu_id` bigint(20) DEFAULT NULL COMMENT '菜单ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=168 DEFAULT CHARSET=utf8 COMMENT='角色与菜单对应关系'
此表设计实现了多对多关系解耦,通过中间表的方式,使得角色和菜单可以灵活配置,支持动态权限分配。
业务核心表设计
fix表负责管理报修业务流程,体现了复杂业务状态的管理能力:
CREATE TABLE `fix` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`project` bigint(20) DEFAULT NULL COMMENT '报修项目',
`price` double(10,2) DEFAULT NULL COMMENT '费用',
`reason` varchar(255) DEFAULT NULL COMMENT '报修原因',
`user` bigint(20) DEFAULT NULL COMMENT '报修人',
`state` varchar(255) DEFAULT NULL COMMENT '维修状态',
`content` text DEFAULT NULL COMMENT '维修说明',
`time` datetime DEFAULT NULL COMMENT '缴费截止时间',
`gmtTime` datetime DEFAULT NULL COMMENT '添加时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='报修信息'
该表设计的精妙之处在于:
price字段使用double(10,2)类型,精确到分,满足财务计算需求state字段采用varchar类型,支持多种状态描述(如"待处理"、"维修中"、"已完成")content字段使用text类型,满足长文本的维修说明存储需求- 双时间戳设计(
time和gmtTime)分别记录业务时间和系统时间,便于业务追踪和系统维护

核心功能实现详解
1. 用户认证与权限控制
系统采用Shiro安全框架实现用户认证和授权。抽象控制器AbstractController提供了统一的用户信息获取方法:
@Component
public abstract class AbstractController {
@Autowired
private SysUserService sysUserService;
protected Logger logger = LoggerFactory.getLogger(getClass());
protected SysUserEntity getUser() {
SysUserEntity sysUserEntity = ShiroUtils.getUserEntity();
SysUserEntity sysUserEntity1 = sysUserService.queryByUserName(sysUserEntity.getUsername());
return sysUserEntity1;
}
protected Long getUserId() {
return getUser().getUserId();
}
}
具体的业务控制器继承该抽象类,即可获得当前登录用户信息:
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
@Autowired
private SysUserService sysUserService;
@GetMapping("/info")
public R info(){
SysUserEntity user = getUser();
return R.ok().put("user", user);
}
@PostMapping("/updatePassword")
public R updatePassword(String password, String newPassword){
Long userId = getUserId();
boolean flag = sysUserService.updatePassword(userId, password, newPassword);
if(!flag){
return R.error("原密码不正确");
}
return R.ok();
}
}

2. 电费计算引擎
系统核心的电费计算功能采用策略模式实现,支持多种电价计算规则:
@Service
public class ElectricityBillingService {
@Autowired
private ElectricityPriceConfigService priceConfigService;
public BillingResult calculateBill(Long userId, Double currentReading, Double previousReading) {
Double usage = currentReading - previousReading;
ElectricityPriceConfig config = priceConfigService.getCurrentConfig();
BillingStrategy strategy;
if ("TIERED".equals(config.getType())) {
strategy = new TieredBillingStrategy();
} else if ("TIME_BASED".equals(config.getType())) {
strategy = new TimeBasedBillingStrategy();
} else {
strategy = new StandardBillingStrategy();
}
return strategy.calculate(usage, config);
}
}
// 阶梯电价策略实现
@Component
public class TieredBillingStrategy implements BillingStrategy {
@Override
public BillingResult calculate(Double usage, ElectricityPriceConfig config) {
Double totalAmount = 0.0;
Double remainingUsage = usage;
for (Tier tier : config.getTiers()) {
if (remainingUsage <= 0) break;
Double tierUsage = Math.min(remainingUsage, tier.getLimit());
totalAmount += tierUsage * tier.getPrice();
remainingUsage -= tierUsage;
}
return new BillingResult(usage, totalAmount, config.getType());
}
}

3. 报修业务流程管理
报修功能实现了完整的工单生命周期管理,从报修提交到维修完成的全流程跟踪:
@Service
public class FixService {
@Autowired
private FixRepository fixRepository;
@Transactional
public FixEntity createFixOrder(FixRequest request) {
FixEntity fix = new FixEntity();
fix.setProject(request.getProjectId());
fix.setReason(request.getReason());
fix.setUser(request.getUserId());
fix.setState("PENDING"); // 初始状态:待处理
fix.setGmtTime(new Date());
fix.setTime(DateUtils.addDays(new Date(), 3)); // 默认3天内处理
return fixRepository.save(fix);
}
@Transactional
public FixEntity updateFixStatus(Long fixId, String status, String content) {
FixEntity fix = fixRepository.findById(fixId)
.orElseThrow(() -> new RuntimeException("报修记录不存在"));
fix.setState(status);
if (content != null) {
fix.setContent(content);
}
return fixRepository.save(fix);
}
public Page<FixEntity> getUserFixOrders(Long userId, Pageable pageable) {
return fixRepository.findByUserOrderByGmtTimeDesc(userId, pageable);
}
}

4. 停电通知管理
news表专门用于管理停电通知信息,支持按片区定向发布:
@Entity
@Table(name = "news")
public class NewsEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String time;
private String pian; // 片区代码
private String content;
@Column(name = "gmtTime")
private Date gmtTime;
// getter和setter方法
}
@Service
public class NewsService {
@Autowired
private NewsRepository newsRepository;
public List<NewsEntity> getNewsByArea(String areaCode, Date startDate, Date endDate) {
Specification<NewsEntity> spec = (root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>();
if (areaCode != null) {
predicates.add(cb.equal(root.get("pian"), areaCode));
}
if (startDate != null && endDate != null) {
predicates.add(cb.between(root.get("gmtTime"), startDate, endDate));
}
return cb.and(predicates.toArray(new Predicate[0]));
};
return newsRepository.findAll(spec, Sort.by(Sort.Direction.DESC, "gmtTime"));
}
}

实体模型设计
系统采用JPA实现对象关系映射,实体类设计遵循Java Bean规范:
/**
* 列属性实体 - 用于代码生成器
*/
public class ColumnEntity {
private String columnName; // 列名
private String dataType; // 列名类型
private String comments; // 列名备注
private String attrName; // 属性名称(首字母大写)
private String attrname; // 属性名称(首字母小写)
private String attrType; // 属性类型
private String extra; // 额外信息(如auto_increment)
// 完整的getter和setter方法
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
// 其他getter/setter方法...
}
这种设计支持自动化的代码生成,提高了开发效率。实体类与数据库表的映射关系通过注解配置:
@Entity
@Table(name = "sys_user")
public class SysUserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@Column(unique = true, nullable = false, length = 50)
private String username;
@Column(length = 100)
private String password;
@Column(length = 100)
private String email;
// 其他字段和方法...
}
功能展望与优化方向
1. 引入Redis缓存提升性能
当前系统在频繁查询的电价配置、用户信息等数据方面可以引入Redis缓存:
@Service
public class CachedElectricityPriceService {
@Autowired
private RedisTemplate<String, ElectricityPriceConfig> redisTemplate;
@Autowired
private ElectricityPriceConfigService priceConfigService;
private static final String PRICE_CACHE_KEY = "electricity:price:current";
public ElectricityPriceConfig getCurrentPriceConfig() {
ElectricityPriceConfig config = redisTemplate.opsForValue().get(PRICE_CACHE_KEY);
if (config == null) {
config = priceConfigService.getCurrentConfig();
redisTemplate.opsForValue().set(PRICE_CACHE_KEY, config, Duration.ofHours(1));
}
return config;
}
}
2. 消息队列实现异步处理
对于短信通知、账单生成等耗时操作,可以引入RabbitMQ实现异步处理:
@Component
public class MessageQueueService {
@Autowired
private AmqpTemplate rabbitTemplate;
public void sendBillNotification(Long userId, Bill bill) {
BillMessage message = new BillMessage(userId, bill);
rabbitTemplate.convertAndSend("bill.exchange", "bill.notification", message);
}
}
@Component
public class BillNotificationConsumer {
@RabbitListener(queues = "bill.notification.queue")
public void processBillNotification(BillMessage message) {
// 异步处理短信发送
smsService.sendBillMessage(message.getUserId(), message.getBill());
}
}
3. 微服务架构改造
将单体应用拆分为微服务,提升系统可扩展性和维护性:
- 用户服务:负责用户管理和认证
- 计费服务:专用于电费计算和账单生成
- 报修服务:处理报修业务流程
- 通知服务:管理停电通知和消息推送
4. 移动端适配与PWA支持
开发响应式前端,支持PWA(渐进式Web应用)技术,提供接近原生应用的体验:
// 注册Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('SW registered: ', registration);
});
}
// 实现离线缓存策略
const CACHE_NAME = 'electricity-app-v1';
const urlsToCache = [
'/',
'/styles/main.css',
'/script/app.js'
];
5. 大数据分析与预测功能
集成大数据分析平台,实现用电趋势预测和异常检测:
@Service
public class ElectricityAnalysisService {
public ConsumptionTrend analyzeTrend(Long userId, int months) {
List<ElectricityUsage> usageData = usageService.getHistoricalUsage(userId, months);
// 使用线性回归分析趋势
SimpleRegression regression = new SimpleRegression();
for (int i = 0; i < usageData.size(); i++) {
regression.addData(i, usageData.get(i).getUsage());
}
return new ConsumptionTrend(
regression.getSlope(),
regression.predict(usageData.size() + 1)
);
}
}
总结
该智能电费管理平台通过SpringBoot框架实现了居民用电计费的全流程数字化管理。系统采用清晰的三层架构,结合JPA实现数据持久化,通过RBAC模型保障系统安全。数据库设计考虑了业务复杂性和性能需求,核心功能涵盖用户管理、电费计算、报修处理、通知发布等关键业务场景。
从技术实现角度看,系统的代码结构清晰,采用了面向对象的设计原则,具备良好的可维护性和扩展性。通过引入缓存、消息队列、微服务等现代化技术手段,可以进一步提升系统性能和用户体验。该平台为传统电力管理业务数字化转型提供了可靠的技术解决方案,具有良好的推广应用价值。