我正在玩 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/