And*_*nea 4 singleton spring dependency-injection inversion-of-control spring-boot
我正在玩Spring Boot,我正在尝试构建一个需要ServiceImpl时要解决的实例Service.目前我正在注释实现,@Component但这并没有让我有机会按我的意愿构建实例.
该ServiceImpl应用含于磁盘上的文件的路径的字符串构成.我想@SpringBootApplication在应用程序类的main方法中执行此操作.
也许只是我来自一个很长的.NET背景,我们通常设置IoC容器,如:
Service service = new Service("C:\\data.bin");
container.RegisterSingleton<IService>(service); // now whoever asks for a IService will receive this precise instance
Run Code Online (Sandbox Code Playgroud)
这在Spring世界有意义吗?
LE:我很清楚GoF单例定义(即阻止其他人创建类的实例) - 我不是针对这个.
在您@SpringBootApplication执行的同一文件中:
@Bean
public IService service() {
return new Service("C:\\data.bin");
}
Run Code Online (Sandbox Code Playgroud)
Spring应该为你自动装配所有东西.默认情况下它应该是单例(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注释之间的区别是什么?).
编辑2:您也不一定要将该@Bean方法放在具有的类中@SpringBootApplication.您可以将它放在任何具有@Configuration注释的类中.
| 归档时间: |
|
| 查看次数: |
10730 次 |
| 最近记录: |