在应用程序启动时将实例注册为“单例”bean

2024-05-27

我正在使用 Spring Boot,我正在尝试构建一个实例ServiceImpl时要解决Service是必须的。目前我将实现注释为@Component但这并没有给我机会构建我想要的实例。

The 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 do:

@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 http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes).

编辑1:您还应该使用 @Service 而不是 @Component 来注释您的 Service 实现(请参阅:Spring中@Component、@Repository和@Service注解有什么区别? https://stackoverflow.com/questions/6827752/whats-the-difference-between-component-repository-service-annotations-in).

编辑2:你也不必把@Bean类中的方法具有@SpringBootApplication。您可以将其放在任何具有以下内容的类中@Configuration注解。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在应用程序启动时将实例注册为“单例”bean 的相关文章

随机推荐