是否存在仅提供依赖注入功能的Spring框架专用依赖库?
在Compose for Desktop中使用Spring纯依赖注入功能
嘿,太懂你这种需求了——想在非Web的桌面项目里用上Spring顺手的DI注解,又不想被Spring Boot Web那些多余的依赖捆住手脚对吧?其实Spring早就把核心的DI功能拆出来了,完全不需要依赖Web相关的包,下面给你一步步讲怎么弄:
需要引入的核心依赖
Spring的依赖注入核心功能主要在spring-context和spring-beans模块里,spring-core是基础支撑,这些都是纯核心库,和Web、MVC完全不沾边。
如果你用的是Gradle Kotlin DSL(毕竟你是Kotlin+Compose项目),直接在build.gradle.kts里加这些依赖:
dependencies { // Spring核心DI相关依赖,版本可以用最新稳定版 implementation("org.springframework:spring-context:6.1.4") implementation("org.springframework:spring-beans:6.1.4") implementation("org.springframework:spring-core:6.1.4") }
要是用Maven的话,pom.xml里加:
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>6.1.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>6.1.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>6.1.4</version> </dependency> </dependencies>
配置DI容器并使用注解
接下来就可以像在Spring项目里一样用@Service、@Component、@Autowired这些注解了,只需要初始化Spring的应用上下文就行:
- 先写一个配置类,用来开启组件扫描:
import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration @Configuration @ComponentScan(basePackages = ["com.yourproject"]) // 替换成你项目的根包路径 class AppConfig
- 在Compose项目的入口处初始化上下文:
import androidx.compose.ui.window.application import org.springframework.context.annotation.AnnotationConfigApplicationContext fun main() { // 初始化Spring DI容器 val context = AnnotationConfigApplicationContext(AppConfig::class.java) // 从容器里获取你的Service实例 val myService = context.getBean(MyService::class.java) application { // 这里写你的Compose UI代码,随时可以用myService或者其他注入的Bean } }
- 写一个带注解的Service类试试:
import org.springframework.stereotype.Service @Service class MyService { fun doSomething() { println("用Spring DI的Service干活啦!") } }
如果需要在其他组件里注入这个Service,直接用@Autowired就行:
import org.springframework.stereotype.Component import org.springframework.beans.factory.annotation.Autowired @Component class AnotherComponent { @Autowired private lateinit var myService: MyService fun useService() { myService.doSomething() } }
额外小提示
- 如果你想要更轻量的方案,甚至可以只引入
spring-beans模块,手动注册Bean,但spring-context提供的组件扫描和自动装配会让开发更省心,推荐用这个。 - 不需要任何Spring Boot的starter依赖,这些纯Spring核心库完全足够支持你的DI需求,不会带来Web相关的冗余代码。
内容的提问来源于stack exchange,提问作者xetra11
相关产品推荐
相关产品推荐

