Skip to content

Repository files navigation

neo

鸿蒙生态的 Koin + Spring 精华 — 轻量 DI 框架 + 实用生态模块

基于 ArkTS 的鸿蒙应用开发框架,提供 IoC/DI、模块化、响应式状态绑定、数据访问、配置管理、事件总线等开箱即用的能力。

核心特性

特性 对标 说明
ServiceManager + Service Spring IoC DI 容器 + 多阶段加载 + 依赖解析
NeoModule Koin Module Koin 式可组合模块,moduleA + moduleB
Scope Koin Scope 页面级作用域,绑定 aboutToAppear/aboutDisappear
StateBinder 鸿蒙独有 Service 数据 → ArkUI @State 响应式桥
DataRepository Spring Repository Preferences / RDB / 内存 统一 CRUD
ConfigService Spring @Value rawfile JSON 加载 + 点号路径访问
ProfileManager Spring Profiles 多环境 dev/staging/prod 切换
EventBus Spring ApplicationEvent 发布/订阅事件总线
CacheService Spring @Cacheable 内存 LRU + TTL 缓存
SchedulerService Spring @Scheduled 定时任务调度
InterceptorChain Spring AOP 轻量拦截器链(日志/性能/错误)
ThemeManager Design Token + 暗色模式 + 主题切换
ValidationService Spring Validator 数据校验框架
ConverterService Spring ConversionService 类型转换
SerializationService 统一序列化(支持 Date/Set/Map)
TestHarness Spring TestContext 测试工具集

快速开始

1. 安装

ohpm install neo

2. 定义 Service

import { Service } from 'neo'

class UserService extends Service {
  private users: Map<string, UserInfo> = new Map()

  constructor(services: Service[]) {
    super(services)
  }

  init() {
    console.info('[UserService] initialized')
  }

  async load(): Promise<boolean> {
    // 加载数据
    return true
  }

  async unload(): Promise<boolean> {
    this.users.clear()
    return true
  }
}

3. 使用 Module 声明依赖

import { NeoModule, GLOBAL_PHASE, BUSINESS_PHASE } from 'neo'

const networkModule = new NeoModule('Network', [
  { tag: 'ApiService', phase: GLOBAL_PHASE, factory: () => new ApiService([]) },
  { tag: 'AuthService', phase: GLOBAL_PHASE, factory: () => new AuthService([]) },
])

const userModule = new NeoModule('User', [
  { tag: 'UserService', phase: BUSINESS_PHASE, factory: () => new UserService([]),
    dependencies: ['AuthService'] },
])

// 模块组合
const appModule = networkModule.merge(userModule)

4. 启动应用

import { serviceManager } from 'neo'

// 在 EntryAbility.onCreate 中:
serviceManager.register(context)
serviceManager.loadModule(appModule)
await serviceManager.loginCallback()

5. 在页面中使用

import { serviceManager, StateBinder } from 'neo'

@Entry
@Component
struct Index {
  @State userList: UserInfo[] = []
  private unbind: (() => void) | undefined

  aboutToAppear() {
    const userService = serviceManager.get<UserService>('UserService')!
    // 响应式绑定:Service 数据变更自动刷新 UI
    this.unbind = StateBinder.bind(userService.getObservable(), this, 'userList')
  }

  aboutToDisappear() {
    this.unbind?.()  // 清理绑定
  }

  build() {
    List() {
      ForEach(this.userList, (user: UserInfo) => {
        ListItem() { Text(user.name) }
      })
    }
  }
}

API 文档

Core — DI 容器

ServiceManager

方法 说明
register(context) 注册应用上下文
load(scene) 加载场景(传统方式)
loadModule(module) 加载 NeoModule(推荐)
loginCallback() 触发启动流程
logoutCallback() 触发卸载流程
get<T>(tag) 获取服务实例
ready(service) 判断服务是否就绪
reset() 重置所有状态

NeoModule

const module = new NeoModule('Name', [
  { tag: 'Svc1', phase: GLOBAL_PHASE, factory: () => new Svc1([]) },
  { tag: 'Svc2', phase: BUSINESS_PHASE, factory: () => new Svc2([]),
    dependencies: ['Svc1'] },
])

module.validate()   // 校验完整性(循环依赖、缺失依赖)
module.merge(other)  // 组合模块
module.load()        // 加载到 ServiceManager

Scope

import { scopeManager } from 'neo'

aboutToAppear() {
  const scope = scopeManager.createScope('SettingsPage')
  scope.bindTo(this)  // 自动绑定页面生命周期
}

// 页面销毁时自动 close scope,unload 所有服务

StateBinder

// Service 端
class UserService extends Service {
  private userObs = new StateBinder.Observable<User[]>([])

  getUserObservable() { return this.userObs }

  async loadUsers() {
    const users = await fetchUsers()
    this.userObs.setValue(users)  // 自动通知 UI
  }
}

// 页面端
StateBinder.bind(service.getUserObservable(), this, 'userList')

Infra — 基础设施

DataRepository

import { PreferenceRepository, MemoryRepository } from 'neo'

// Preferences KV 存储
const repo = new PreferenceRepository<User>('users', context)
await repo.save('u1', { name: 'Alice', age: 30 })
const user = await repo.findById('u1')

// 内存存储(测试用)
const memRepo = new MemoryRepository<User>()

ConfigService

import { ConfigService } from 'neo'

const config = new ConfigService(context)
await config.load('config.json')
const host = config.getString('database.host', 'localhost')
const port = config.getNumber('database.port', 3306)

EventBus

import { eventBus } from 'neo'

const unsub = eventBus.on('user:login', (payload) => {
  console.info('User logged in')
})

eventBus.emit('user:login', { userId: 'u1' })
unsub()  // 取消订阅

CacheService

import { CacheService } from 'neo'

const cache = new CacheService(100, 300000)  // max 100 items, default TTL 5min
cache.set('user:u1', userData, 60000)
const user = cache.get<UserData>('user:u1')

// 带自动加载
const data = await cache.getOrLoad('expensive:key', async () => {
  return await fetchExpensiveData()
}, 120000)

ThemeManager

import { themeManager } from 'neo'

const tokens = themeManager.current()
// tokens.colors.primary, tokens.typography.body.fontSize, tokens.spacing.md

themeManager.setDarkMode(true)    // 切换暗色
themeManager.applyTheme('brand')  // 应用自定义主题

InterceptorChain

import { InterceptorChain, LogInterceptor, PerfInterceptor } from 'neo'

const chain = new InterceptorChain([
  new LogInterceptor(),
  new PerfInterceptor(500),
])

const result = await chain.execute('UserService', 'load', async () => {
  return await userService.load()
})

ValidationService

import { ValidationService } from 'neo'

const validator = new ValidationService()
validator.addRules({
  name: { required: true, minLength: 2 },
  email: { required: true, pattern: /^.+@.+\..+$/ },
  age: { required: true, min: 0, max: 150 },
})

const errors = validator.validate({ name: 'A', email: 'bad', age: -1 })

多阶段加载

neo 提供 4 个预定义阶段,按优先级自动排序加载:

阶段 优先级 策略 用途
GLOBAL 10 串行等待 基础设施(配置/数据库/网络)
BUSINESS 20 串行等待 核心业务(用户/认证/订单)
FEATURE 30 并行触发 功能服务(统计/通知/推荐)
LAZY 40 并行触发 非关键服务(日志/分析)

自定义阶段:

import { createPhase } from 'neo'

const CACHE_PHASE = createPhase({
  name: 'CACHE',
  priority: 25,
  waitForComplete: false,
  description: '缓存预热'
})

项目结构

neo/
├── Index.ets                    # Barrel export
├── oh-package.json5             # OHPM 包配置
├── core/                        # DI 核心
│   ├── Service.ets              #   服务基类
│   ├── ServiceManager.ets       #   IoC 容器
│   ├── PhaseConfig.ets          #   Phase 定义
│   ├── DefaultPhases.ets        #   预定义阶段
│   ├── Scene.ets                #   场景接口
│   ├── AppPropagation.ets       #   核心接口
│   ├── ServiceLifeCycle.ets     #   生命周期枚举
│   ├── NeoModule.ets       #   可组合模块
│   ├── Scope.ets                #   页面级作用域
│   ├── StateBinder.ets          #   响应式状态绑定
│   └── Interceptor.ets          #   拦截器接口 + 链
├── infra/                       # 基础设施
│   ├── data/                    #   数据访问层
│   ├── config/                  #   配置管理
│   ├── event/                   #   事件总线
│   ├── cache/                   #   缓存服务
│   ├── scheduler/               #   定时任务
│   ├── log/                     #   日志服务
│   ├── interceptors/            #   内置拦截器
│   ├── validation/              #   数据校验
│   ├── converter/               #   类型转换
│   ├── serialization/           #   序列化
│   └── test/                    #   测试工具
├── theme/                       # 设计系统
│   ├── Theme.ets                #   Design Token
│   └── ThemeManager.ets         #   主题管理
└── examples/                    # 示例应用

License

MIT

About

基于一种通用中小型基于ArkTS的鸿蒙应用开发框架的架构约束

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages