Spring: Start refresh knowledges

As a preparation to relocate, I start to refresh my knowledges about some tools — frameworks, programming languages features, some WTF places for me in system design etc.

First objective — Spring Framework and I started with Spring Context — heart of framework.

Some reminders about Spring context:

Add beans to context:

Beans — instances of objects, added to Spring Context

  1. Method to add beans by @Bean
    Configuration class (anotated with @Configuration) — various Spring-related configurations:
    can added @Bean classes to context — beans: @Bean instruct Spring to call this method at context initialization
    method name becomes the bean’s name
    @Bean(name = «miki») — to change name of bean.
  1. Method to add beans by stereotype
    (some comments — @Primary annotation — make exemplar of bean primary)
    @Component — Spring creates an instance of the class and adds that instance to its context
    Also, we have configuration class — marks by @Configuration and @ComponentScan(basePackages=«»)
    @PostConstruct to manage instance atfer its creation
    @PreDestroy — before closing context.
  1. Method to add beans programmaticaly — by registerBean on ApplicationContext,

Scope of Beans

Scope is an approach for creating and managing beans and their lifecycles.

The default scope of bean is singleton.
Spring allows multiple instance of similar type  — singleton by uniqie name: unqiue per name not unique per app.

Singleton beans must be immutable. Singleton beans can be used in multi-threaded environment, but synchronization is not good decision/practice in this situation.

Spring create all singleton beans when context is initialized — this is default behavior of framework. These is eager instantiation. But we can annotate with @Lazy to power on lazy instantiation.
Trade-off: if some beans can’t created in lazy instantiation — running application will throws exceptions.
Also — when framework needed to create @Lazy @Bean by first referred call, it’s start to check if instances exists, and then eventually create one — not good for performance point of view.

To change scope — add annotation @Scope and specialized:

@Scope(BeanDefinition.SCOPE_PROTOTYPE)
  • to set prototype
@Scope(BeanDefinition.SCOPE_SINGLETON)
  • to set singleton.

Main reminder: to create prototype beans — need to get bean exemplar from context, like this:

CommentProcessor p = context.getBean(CommentProcessor.class);
p.setComment(c);
p.processComment(c);
p.validateComment(c);
c = p.getComment();

Singleton — Spring Context controls by instance: name to instance, protorype — controls by type: name to type.
With prototype each thread has it’s own instance of bean.