spring - 在应用程序启动时将实例注册为 'singleton' bean

标签 spring spring-boot dependency-injection singleton inversion-of-control

我正在玩 Spring Boot,我正在尝试构建一个 ServiceImpl 的实例。待解决当Service是必须的。目前我将实现注释为 @Component但这并没有给我机会按照我的意愿构建实例。
ServiceImpl应该使用包含磁盘上文件路径的字符串构造。我想在 @SpringBootApplication 的主要方法中执行此操作应用程序的类别。

也许只是我来自一个很长的 .NET 背景,我们通常会像这样设置 IoC 容器:

Service service = new Service("C:\\data.bin");
container.RegisterSingleton<IService>(service); // now whoever asks for a IService will receive this precise instance

这在 Spring 世界中有意义吗?

LE:我很清楚 GoF 单例定义(即防止其他人创建类的实例)——我不是针对这个。

最佳答案

在您拥有 @SpringBootApplication 的同一文件中做:

@Bean
public IService service() {
    return new Service("C:\\data.bin");
}

Spring 应该为你自动连接一切。默认情况下它应该是单例( http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes )。

编辑 1:您还应该使用 @Service 而不是 @Component 注释您的 Service 实现(请参阅: What's the difference between @Component, @Repository & @Service annotations in Spring? )。

编辑 2:您也不一定非要放置 @Bean具有 @SpringBootApplication 的类中的方法.你可以把它放在任何具有 @Configuration 的类中。注解。

关于spring - 在应用程序启动时将实例注册为 'singleton' bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40869870/

相关文章:

java - 对服务的 Dagger 依赖项注入(inject)失败并显示 "contactServiceModule must be set at DaggerAppComponent$Builder.build(DaggerAppComponent.java)"

java - Spring - 在 Java 配置类中注入(inject)构造函数参数

java - java.lang.ClassNotFoundException 的未知原因

java - 使用倒计时闩锁或 Spring 集成并行调用 Web 服务哪个更好?

java - Junit 测试中的 RestTemplate 模拟,mockRestTemplate.postForObject() 返回 null

java - 在 Spring MVC 应用程序属性文件中使用阿拉伯字符串

java - Dagger 2 : error while getting a multiple instances of same object with @Named

java - 如何为部署到 WAS 8 的 spring 4/hibernate 4.3 应用程序配置事务管理

java - Spring REST如何支持带有列表和对象的JSON

java - 无法使用 SpringSource Tool Suite 计算构建计划