Skip to main content

Annotations and Scope in Spring:

 Basic Annotations:

Component:

  • It is used to create the bean without the configuration files like xml and java configurations
  • The auto wired is used along with it to do the dependency injection

Autowired:

  • The Autowired annotation is used for the dependency injection the main types are the:
  1. Autowired in constructor
  2. Autowired in setter
  3. Autowired in the field
Note: Using the field injection is not recommended.
Fig 1. Autowired in constructor.

Fig 2. Autowired in the field.

Import:

  • It is used to import other configuration files into the class file. 
  • This will be helpful in the scenario of multiple configuration files are there.
Fig 3. Import method usage

Primary:

  • The @Primary annotation can be present at the starting of a class where it represent the primary class. For example if we implement two classes using a interface and we gave two classes the @Component annotation the spring will be confused. 
  • So when we add the primary tag on any one of them then that one will be chosen 1st.
  • We can not use primary in more than one bean.

Qualifier:

  • When we don't want to write code on the dependency we can write the code for priority in the dependent tag itself.
  • When we write the @Autowired annotation in next line we write the @Qulifier("name") to set that as the primary Dependency Injection.
  • It is used to set name or alias name to bean and based on qualifier the bean will executes corresponding backend system.

Definition(CS):

  • The process of Spring Framework lookup for identify @Component annotation and then creating object is called Component Scan.
  • The Component Scan is not explicitly enabled so we need to enable it in xml or java configuration files using the @Componentscan("Path") annotation.
  • We can also specify the exact name of the classes no the path using (basePackageClasses = {classname.class, ..}).
  • The Component scan will also work with only the @Bean without the component . But we need the XML configuration. 
Combinations we can use:
  • xml config
  • xml with java config
  • java config with Autowired.

Lazy:

  • @Lazy annotation is used to create the object when first request will come instead of scan and create object during startup.
  • It indicates that a bean will be lazily initialized.
  • The lazy annotation can be annotated with class level (@Component,@Configuration) and method level (@Bean) .
  • Generally singleton beans are pre initialized to discover the errors in the configuration. So if we don't want to initialize a bean lazily we can use @Lazy in Java configuration or use lazy-init attribute in <bean> element in XML configuration.
  • If we want to use the Lazy annotation but want early initialization then use (@Lazy(value=false)).
  • Bean will not be initialized until referenced or called by another bean. And also when explicitly called that bean from ApplicationContext.
  • @Lazy can be also used in the @Autowired annotation configuration.

Note:

  1. If we use XML we can easily migrate to other methods like java config and annotations.
  2. If we use java config or autowired then it is difficult to migrate from Java to other framework.

Spring Scope:

  • Bean Scope - Life Time of the Bean in the container.
  • When a bean gets created by container and when it gets destroyed this lifecycle is the bean scope.

Types of Scopes in Spring: 

  1. Singleton
  2. Prototype
  3. Request
  4. Session
  5. Global
  6. Application
Note: The core scopes are singleton and prototype.

Singleton:

  • Singleton bean will be created and will be in the container till it is deleted.
  • When only one object is created for multiple requests then it is called singleton.
  • Or in other words only one object per container and per bean definition.
  • It will be created during container startup. And destroyed during container is destroyed.
  • Singleton Scope is not same as Java Singleton design pattern.(one object for whole application in java DP but in here one object for one container).
  • eg: <bean id = "abc" class="ABC"> <bean id = "abc1" …>
  • This means for single bean there would be single object only.
  • If we create multiple objects with same bean then those objects are same in every aspects nothing change is there between them(container has only one object and provide it every where).
Prototype:
  • Multiple objects per bean definition per container. That means whenever there is a need for a bean a new object is created like use and throw.
  • Spring Container always holds reference singleton beans which it has created as it is reused using that reference but spring container does not hold any reference of the prototype beans which it has created.
  • Once the object completes its part then it will be collected by JVM.
Note:  By default all spring beans are Singleton scope

  • In XML config <bean id = … class = … scope = "prototype">
  • In Java config @Scope(…).
Fig 4. Scoping in Java Configuration.




When we can go for singleton and prototype ?
  • There are four case are there:
  • 1: Singleton -> Singleton
  • 2: Prototype -> Prototype
  • 3: Singleton -> Prototype
  • 4: Prototype -> Singleton
Note:  Never inject a shorter lived bean into a longer live bean.

Example: 
  • The project flow may be like this: Controller => service => DAO => Database.
  • If we inject a singleton DAO to a singleton controller then the object will be same for any requests. This does not create a problem
  • And for prototype prototype is also no problem. And also the singleton to a prototype injection is also no problem because the dependency is a singleton so no changes will happen for what ever the dependent changes.
  • But as per note above if we inject a prototype into a singleton then there arises a problem. So a singleton bean is created and it will be permanent but the prototype will be change so the 1st prototype bean only be injected into the singleton all the other instances of prototypes are not use(prototype behave like singleton).
The Conditions to usage of different scopes:
  • If a class will not have any instance variable then prefer singleton.(class does not hold any state)
  • If class will have any instance variable then prefer prototype  because instance will be varied from object to object(request).

Comments

Popular posts from this blog

Java Spring Framework:

CORE: BASICS:           The new technology I had learned is the spring Framework core which is the base of the Spring technology or framework in Java. The main feature of the spring is that it is light weight where the run time is very less. Then the next advantage is the framework use the dependency injection in the object reference in Java where java is a OOPs programming language. The spring framework was found by rod johnson in the year of 2002 and licensed in the apache company in 2003. The other advantages of the Spring is that it can be used to build every application or software which is currently in the market. The framework supports: AOP Spring Boot Spring JDBC Spring MVC Spring EJB Spring Hibernate.           The diagram from the official website of the Spring is a good representation of the Spring Framework architecture which relies on the Spring Core. Fig 1: Spring Framework       ...

Properties and Primitive Insertion in Spring:

 Property Files and Values: The Properties is a subclass of Hashtable class and it represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string. .properties is a file extension for files mainly used in Java-related technologies to store the configurable parameters of an application The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties.load() method of Properties class is convenient to load .properties file in the form of key-value pairs. In normal java syntax we will use the util.*. to load the properties, URL,  etc. Then we use the load method to load any file and we can use that to retrieve properties. But in spring we can use only one annotation to load the whole properties file and the Annotation is @PropertySource:(file path). The main important job of the property file is to reduce the har...