问题描述
我想实现一个功能,在该功能中,我应该在部署时从数据库中加载对象列表.该数据库已经完成了各自的实现,并且正在使用中.
I want to implement a feature in which at deploy time, I should load list of objects from Database. The database already have respective implementaiton done which is being used on the fly.
鉴于我是Spring的新手,所以我试图了解spring的不同功能,我可以利用这些功能来实现此功能.如果我不使用Spring,我会
Given that I am new to Spring, I am trying to understand different features of spring which i can leverage to implement this feature. If i wasn't using Spring, I would have
- 创建了线程安全的单例类
- 通过servlet生命周期在应用程序加载时加载该类
- 加载该Singleton类中的所有内容,并覆盖现有的db类,以在发出查询之前检查此Singleton类.这样,仅当出于某些原因未加载此类时才发出查询.
现在,在春天,我是如此困惑.我一直在撰写不同的文章,并试图找到一些建议.首先,我应该使用@Component
来使类成为单例吗?弹簧会照顾螺纹的安全性吗?
Now, In spring, I am so confuse. I have been reaidng different articles and trying to find some pointers. First of all, shall i use @Component
to make the class singleton ? Would spring take care of thread safety?
第二,该类是spring的Service
类吗?我是否必须用@Service
进行注释?
Secondly, Would this class be a Service
class for spring ? Do i have to annotate it with @Service
?
第三,我应该在启动时使用@PostConstruct
加载此类吗?还是还有其他更好的选择?
Third, shall i use @PostConstruct
to load this class at startup ? Or there are other better options ?
推荐答案
以下是您的问题的答案:
Here are the answers to your questions:
首先,我应该使用@Component来使类成为单例吗?弹簧会照顾螺纹的安全性吗?
@Component
用于基于XML的Spring Configuration中的组件扫描,以创建Spring Bean. Bean将创建任何类的Singleton实例.
@Component
is used for Component Scaning in XML based Spring Configuration to create the Spring Beans. A Bean will create a Singleton Instance of any Class.
其次,该课程将成为spring的Service课程吗?我必须用@Service
进行注释吗?
Secondly, Would this class be a Service class for spring? Do I have to annotate it with @Service
?
@Service
只是@Component
的特化.如果您继续使用@Service
或@Repository
或将其替换为@Component
,则完全可以.
@Service
is nothing but a Specialization of @Component
. It's completely fine if you continue to use @Service
or @Repository
or replace them with @Component
.
第三,我是否应该在启动时使用@PostConstruct
加载此类?还是还有其他更好的选择?
Third, shall I use @PostConstruct
to load this class at startup? Or there are other better options?
@PostConstruct
将在创建bean之后仅运行一次.如果您希望在应用程序首次启动时将数据从数据库加载到缓存等中,则可以使用它.
@PostConstruct
will run only once after the bean creation. It can be used if you want to load the data from DB to your cache etc. when your application starts for the first time.
这篇关于了解Spring Singleton在启动时加载实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!