4

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.

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

  • Created a Thread-Safe Singleton Class
  • Load that class at application load time by servlet life-cycle
  • Load everything in that Singleton Class and override existing db class to check this singleton class before issuing query. This way a query will be issued only if this class hasn't loaded for some reason.

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?

Secondly, Would this class be a Service class for spring ? Do i have to annotate it with @Service ?

Third, shall i use @PostConstruct to load this class at startup ? Or there are other better options ?

Em Ae
  • 8,167
  • 27
  • 95
  • 162

1 Answers1

5

Here are the answers to your questions:

First of all, shall i use @Component to make the class singleton? Would spring take care of thread safety?

@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.

Secondly, Would this class be a Service class for spring? Do I have to annotate it with @Service?

@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.

Third, shall I use @PostConstruct to load this class at startup? Or there are other better options?

@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.

user2004685
  • 9,548
  • 5
  • 37
  • 54
  • 1
    So based on your suggestion, this code will serve the purpose i am looking for http://pastebin.com/yHEE5xaQ. So this class, will automatically be called on applicaiton deployment and its post-construct method will load everything ... am i right ? – Em Ae Feb 02 '16 at 18:11
  • I forgot to ask that how would i access this class ? Shall i access it like a normal class i.e., `MyEntityCache me = new MyEntityCache()`? Or shall i fetch through Spring context ? – Em Ae Feb 02 '16 at 20:28
  • You can inject it using `@Autowired` annotation. – user2004685 Feb 02 '16 at 20:38
  • Yeah, i figured that out. Thanks though :) – Em Ae Feb 02 '16 at 20:39
  • Does it still not answer your question? – user2004685 Feb 02 '16 at 20:40