What is Spring framework?
Spring framework is an open source framework created to solve the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use. Main module for Spring are Spring core,Spring AOP and Spring MVC.
How does spring work internally?
The Spring IoC container
It is the heart of the Spring Framework. The IoC container receives metadata from either an XML file, Java annotations, or Java code. The container gets its instructions on what objects to instantiate, configure, and assemble from simple Plain Old Java Objects (POJO) by reading the configuration metadata provided. These created objects through this process called Spring Beans.
The responsibilities of IoC container are:
Instantiating the bean
Wiring the beans together
Configuring the beans
Managing the bean’s entire life-cycle
This diagram represents an abstract view of the working of the Spring Framework. It shows how Spring makes use of Java POJO classes and configuration metadata.
The real benefits of Spring are showing up through its wiring constructs and using auto-wiring.
Actually by default Spring does not do any bytecode postprocessing neither for XML-, nor annotation-configured beans. Instead relevant beans are wrapped into dynamic proxies (see e.g. java.lang.reflect.Proxy in the Java SDK). Dynamic proxies wrap the actual objects you use and intercept method calls, allowing to apply AOP advices. The difference is that proxies are essentially new artificial classes created by the framework, whereas weaving/bytecode postprocessing changes the existing ones. The latter is impossible without using the Instrumentation API you mentioned.
As for the annotations, the implementation of <context:component-scan> tag will scan the classpath for all classes with the Spring annotations and create Spring metadata placeholders for them. After that they are treated as if they were configured via XML (or to be more specific both are treated the same).
Although Spring doesn't do bytecode postprocessing itself you can configure the AspectJ weaving agent that should work just fine with Spring, if proxies do not satisfy you. Read this for more info.
In a nutshell, if you are not using any @Transactional or any other AOP, proxy will not be created. Spring will directly used the original created object, otherwise ayour class will be wrapped into a proxy and then this proxy will be invoked everytime.
Read this and this.
Explain main modules of Spring ?
Spring AOP:
One of the key components of Spring is the AOP framework. AOP is used in Spring:
To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring’s transaction abstraction.
To allow users to implement custom aspects, complementing their use of OOP with AOP
Spring ORM:
The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.
Spring Web:
The Spring Web module is part of Spring?s web application development stack, which includes Spring MVC.
Spring DAO:
The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
Spring Context:
This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
Spring Web MVC:
This is the Module which provides the MVC implementations for the web applications.
Spring Core:
The Core package is the most import component of the Spring Framework.
This component provides the Dependency Injection features. The BeanFactory provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic.
What is dependency injection(IOC) in Spring?
The basic concept of the dependency injection (also known as Inversion of Control pattern) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.
Inversion of control is a design paradigm with the goal of giving more control to the targeted components of your application, the ones that are actually doing the work.
Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality. Inversion of control relies on dependency injection because a mechanism is needed in order to activate the components providing the specific functionality. Otherwise how will the framework know which components to create if it is no longer in control?
In Java, dependency injection may happen through 3 ways:
A constructor injection
A setter injection
An interface injection
Explain IoC in Spring Framework?
The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container.
The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container interface in Spring.
IOC Container : Bean Factory & Application Context
Dependency Injection in Spring :
Dependency Injection via Setter method
Setter Injection in Spring is a type of dependency injection in which the framework injects the dependent objects into the client using a setter method. The container first calls the no argument constructor and then calls the setters. The setter based injection can work even If some dependencies have been injected using the constructor.
EX :
public class Country {
String countryName;
Capital capital;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Capital getCapital() {
return capital;
}
public void setCapital(Capital capital) {
this.capital = capital;
}
}
ApplicationContext.xml
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
<property name="countryName" value="India"/>
<property name="capital" ref="CapitalBean"/>
</bean>
Dependency Injection via Constructor
the DI will be injected with the help of contructors. Now to set the DI as CDI in bean, it is done through the bean-configuration file For this, the property to be set with the CDI is declared under the <constructor-arg> tag in the bean-config file.
public class GFG {
// The object of the interface IGeek
IGeek geek;
// Constructor to set the CDI
GFG(IGeek geek)
{
this.geek = geek;
}
}
<bean id="GFG" class="com.geeksforgeeks.org.GFG">
<constructor-arg>
<bean class="com.geeksforgeeks.org.impl.CsvGFG" />
</constructor-arg>
</bean>
What is Bean in Spring?
A normal POJO class managed by Spring IOC container are called Spring beans. It is core part of Spring application.
How can you configure Spring in your application?
There are 3 ways to do it.
XML based configuration
Java based configuration
Annotation based configuration.
What is Spring XML based configuration?
In Spring XML based configuration, you define all dependency in an XML file. You define all your beans with tag in XML file and all dependencies are read using this XML file.
A Spring XML Configuration uses Spring namespaces to make available the sets of XML tags used in the configuration; the main Spring namespaces are: context, beans, jdbc, tx, aop, mvc, aso.
<beans>
<!-- JSON Support -->
<bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
</beans>
ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
What is Spring java based configuration?
In Spring Java based configuration, you inject all dependencies using java class only. You can use @Configuaration and @Bean annotations to do it.
Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions. Furthermore, @Configuration classes allow inter-bean dependencies to be defined by simply calling other @Bean methods in the same class.
The @Bean annotation is used to indicate that a method instantiates, configures and initializes a new object to be managed by the Spring IoC container. @Bean annotation plays the same role as the <bean/> element.
To enable component scanning, just annotate your @Configuration class as follows:
@Configuration
@ComponentScan(basePackages = "com.howtodoinjava")
public class AppConfig {
...
}
package org.arpit.java2blog.config;
import org.arpit.java2blog.model.Country;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationConfiguration {
@Bean(name="countryObj")
public Country getCountry()
{
return new Country("India");
}
}
Above file is equivalent to below spring configuration xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<bean id="countryObj" class="org.arpit.java2blog.Country" >
<property name="countryName" value="India"/>
</bean>
</beans>
To get above bean to application context, you need to use below code
ApplicationContext appContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
Country countryObj = (Country) appContext.getBean("countryObj");
What is spring annotation based configuration?
You can do dependency injection via annotation also instead of XML configuration. You can define bean autowiring using annotations. You can use @Component,@Repository,@Service and @Controller annotation to configure bean in Spring application.
Annotations wiring is not turned on by default. You need to turn it on using :
<?xml version="1.0" encoding="UTF-8"?>
<bean>
<context:annotation-config/>
</beans>
Once you put above code, you can start using annotation on class , fields or methods.
Few important annotations which you will be using in this type of configuration are :
@Required : The @Required annotation applies to bean property setter methods.
@Autowired : The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.
@Qualifier : The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
JSR-250 Annotations : Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.
Use this for Complete Java Example.
FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
How to create ApplicationContext in a Java Program?
There are following ways to create spring context in a standalone java program.
AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.
FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
What are different bean scopes in Spring?
There are 5 types of bean scopes supported in spring
singleton – Scopes a single bean definition to a single object instance per Spring IoC container(per Application Context).
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request.
session – Return a single bean instance per HTTP session.
globalSession – Return a single bean instance per global HTTP session.
What is default scope of bean in Spring?
singleton is default scope of a bean in Spring. You have to explicitly change scope of a bean if you want different scope.This is one of most asked spring interview questions.
What is ApplicationContext and what are its functions?
ApplicationContext is an central interface for providing configuration information to an application.
An ApplicationContext provides the following functionalities:
Bean factory methods, inherited from ListableBeanFactory. This avoids the need for applications to use singletons.
The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
The ability to publish events. Implementations must provide a means of registering event listeners.
Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.
How do you injection collection in Spring?
You can initialize collection using list and value tag as below:
<bean id="CountryBean" class="org.arpit.java2blog.Country">
<property name="listOfStates">
<list>
<value>Himachal Pradesh</value>
<value>West Bengal</value>
<value>Gujrat</value>
</list>
</property>
</bean>
What do you mean by bean autowiring in Spring?
In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in .The Spring container can autowire relationships between collaborating beans without using and elements which helps cut down on the amount of XML configuration
<bean id="countryBean" class="org.arpit.java2blog.Country" autowire="byName">
difference between dependency injection and autowiring
Dependency Injection is a design pattern, and @autowired is a mechanism for implementing it.
The DI idea is that, instead of your object creating an object it needs (say by using new to instantiate it), this needed object - a dependency - is handed to your object, typically using the constructor or a setter method. If you autowire, you're injecting a dependancy. In this case, Spring uses reflection to make this work, so you're not using the constructor or a setter method, but you're still injecting the dependency.
Error safe autowiring with ‘required=false’
Even if you have used utmost care in autowiring bean dependencies, still you may find strange lookup failures. So, solve this issue, you will need to make autowiring optional so that if no dependency is found, application should not throw any exception and autowiring should simply be ignored.
This can be done in two ways:
If you want to make specific bean autowiring non-mandatory for a specific bean property, use required=”false” attribute in @Autowired annotation.
EmployeeBean.java
@Autowired (required=false)
@Qualifier ("finance")
private DepartmentBean departmentBean;
If you want to apply optional autowiring at global level i.e. for all properties in all beans; use below configuration setting.
beans.xml
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
<property name="requiredParameterValue" value="false" />
</bean>
Difference between @Autowired , @Resource and @Inject annotation in Spring?
@Autowire , @Inject, @Resource they all server the same purpose
The main difference is that, @Autowired and @Inject works similar for 100% without any differentiation.These two annotations using AutowiredAnnotationBeanPostProcessor to inject dependencies. But,@Resource uses CommonAnnotationBeanPostProcessor to inject dependencies and there is difference in the order of checking.
@Autowired and @Inject
Matches by Type
Restricts by Qualifiers
Matches by Name
@Resource
Matches by Name
Matches by Type
Restricts by Qualifiers (ignored if match is found by name)
The @Inject annotation also serves the same purpose, but the main difference between them is that @Inject is a standard annotation for dependency injection and @Autowired is spring specific
Ref: https://javabeat.net/difference-resource-autowired-inject-spring-injection/
@Inject and @Named Annotations Difference
JSR-330 annotations.
@Inject instead of Spring’s @Autowired to inject a bean.
@Named instead of Spring’s @Component to declare a component/bean.(@Component can be referred from my previous post Classpath Scaning)
What are different modes of autowiring supported by Spring?
There are following autowiring modes which can be used to instruct Spring container to use autowiring for dependency injection.
no:
Default, no auto wiring, set it manually via “ref” attribute as we have done in dependency injection via settor method post.
byName:
Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file and it tries to match it with name of bean in xml configuration file.
byType:
Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.
contructor:
byType mode in constructor argument.
autodetect:
Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
@Resource annotation in spring
The @Resource annotation in spring performs the autowiring functionality. This annotation follows the autowire=byName semantics in the XML based configuration i.e. it takes the name attribute for the injection. Below snippet shows how to use this annotation.
What's the difference between @Component, @Repository & @Service annotations in Spring?
From Spring Documentation:
The @Repository annotation is a marker for any class that fulfils the role or stereotype of a repository (also known as Data Access Object or DAO). Among the uses of this marker is the automatic translation of exceptions, as described in Exception Translation.
Spring provides further stereotype annotations: @Component, @Service, and @Controller. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases (in the persistence, service, and presentation layers, respectively). Therefore, you can annotate your component classes with @Component, but, by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects.
For example, these stereotype annotations make ideal targets for pointcuts. @Repository, @Service, and @Controller can also carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated earlier, @Repository is already supported as a marker for automatic exception translation in your persistence layer.
┌──────────────┬─────────────────────────────────────────────────────┐
│ Annotation │ Meaning │
├──────────────┼─────────────────────────────────────────────────────┤
│ @Component │ generic stereotype for any Spring-managed component │
│ @Repository │ stereotype for persistence layer │
│ @Service │ stereotype for service layer │
│ @Controller │ stereotype for presentation layer (spring-mvc) │
└──────────────┴─────────────────────────────────────────────────────┘
Spring framework is an open source framework created to solve the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use. Main module for Spring are Spring core,Spring AOP and Spring MVC.
How does spring work internally?
The Spring IoC container
It is the heart of the Spring Framework. The IoC container receives metadata from either an XML file, Java annotations, or Java code. The container gets its instructions on what objects to instantiate, configure, and assemble from simple Plain Old Java Objects (POJO) by reading the configuration metadata provided. These created objects through this process called Spring Beans.
The responsibilities of IoC container are:
Instantiating the bean
Wiring the beans together
Configuring the beans
Managing the bean’s entire life-cycle
This diagram represents an abstract view of the working of the Spring Framework. It shows how Spring makes use of Java POJO classes and configuration metadata.
The real benefits of Spring are showing up through its wiring constructs and using auto-wiring.
Actually by default Spring does not do any bytecode postprocessing neither for XML-, nor annotation-configured beans. Instead relevant beans are wrapped into dynamic proxies (see e.g. java.lang.reflect.Proxy in the Java SDK). Dynamic proxies wrap the actual objects you use and intercept method calls, allowing to apply AOP advices. The difference is that proxies are essentially new artificial classes created by the framework, whereas weaving/bytecode postprocessing changes the existing ones. The latter is impossible without using the Instrumentation API you mentioned.
As for the annotations, the implementation of <context:component-scan> tag will scan the classpath for all classes with the Spring annotations and create Spring metadata placeholders for them. After that they are treated as if they were configured via XML (or to be more specific both are treated the same).
Although Spring doesn't do bytecode postprocessing itself you can configure the AspectJ weaving agent that should work just fine with Spring, if proxies do not satisfy you. Read this for more info.
In a nutshell, if you are not using any @Transactional or any other AOP, proxy will not be created. Spring will directly used the original created object, otherwise ayour class will be wrapped into a proxy and then this proxy will be invoked everytime.
Read this and this.
Explain main modules of Spring ?
Spring AOP:
One of the key components of Spring is the AOP framework. AOP is used in Spring:
To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring’s transaction abstraction.
To allow users to implement custom aspects, complementing their use of OOP with AOP
Spring ORM:
The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.
Spring Web:
The Spring Web module is part of Spring?s web application development stack, which includes Spring MVC.
Spring DAO:
The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
Spring Context:
This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
Spring Web MVC:
This is the Module which provides the MVC implementations for the web applications.
Spring Core:
The Core package is the most import component of the Spring Framework.
This component provides the Dependency Injection features. The BeanFactory provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic.
What is dependency injection(IOC) in Spring?
The basic concept of the dependency injection (also known as Inversion of Control pattern) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.
Inversion of control is a design paradigm with the goal of giving more control to the targeted components of your application, the ones that are actually doing the work.
Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality. Inversion of control relies on dependency injection because a mechanism is needed in order to activate the components providing the specific functionality. Otherwise how will the framework know which components to create if it is no longer in control?
In Java, dependency injection may happen through 3 ways:
A constructor injection
A setter injection
An interface injection
Explain IoC in Spring Framework?
The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container.
The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container interface in Spring.
IOC Container : Bean Factory & Application Context
Dependency Injection in Spring :
Dependency Injection via Setter method
Setter Injection in Spring is a type of dependency injection in which the framework injects the dependent objects into the client using a setter method. The container first calls the no argument constructor and then calls the setters. The setter based injection can work even If some dependencies have been injected using the constructor.
EX :
public class Country {
String countryName;
Capital capital;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Capital getCapital() {
return capital;
}
public void setCapital(Capital capital) {
this.capital = capital;
}
}
ApplicationContext.xml
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
<property name="countryName" value="India"/>
<property name="capital" ref="CapitalBean"/>
</bean>
Dependency Injection via Constructor
the DI will be injected with the help of contructors. Now to set the DI as CDI in bean, it is done through the bean-configuration file For this, the property to be set with the CDI is declared under the <constructor-arg> tag in the bean-config file.
public class GFG {
// The object of the interface IGeek
IGeek geek;
// Constructor to set the CDI
GFG(IGeek geek)
{
this.geek = geek;
}
}
<bean id="GFG" class="com.geeksforgeeks.org.GFG">
<constructor-arg>
<bean class="com.geeksforgeeks.org.impl.CsvGFG" />
</constructor-arg>
</bean>
Setter Dependency Injection (SDI) vs. Constructor Dependency Injection (CDI)
SETTER DI | CONSTRUCTOR DI |
---|---|
The bean must include getter and setter methods for the properties. | The bean class must declare a matching constructor with arguments. Otherwise, BeanCreationException will be thrown. |
Circular dependencies or partial dependencies result with Setter DI because object creation happens before the injections. | No scope for circular or partial dependency because dependencies are resolved before object creation itself. |
Preferred option when properties are less and mutable objects can be created. | Preferred option when properties on the bean are more and immutable objects (eg: financial processes) are important for application. |
A normal POJO class managed by Spring IOC container are called Spring beans. It is core part of Spring application.
How can you configure Spring in your application?
There are 3 ways to do it.
XML based configuration
Java based configuration
Annotation based configuration.
What is Spring XML based configuration?
In Spring XML based configuration, you define all dependency in an XML file. You define all your beans with tag in XML file and all dependencies are read using this XML file.
A Spring XML Configuration uses Spring namespaces to make available the sets of XML tags used in the configuration; the main Spring namespaces are: context, beans, jdbc, tx, aop, mvc, aso.
<beans>
<!-- JSON Support -->
<bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
</beans>
ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
What is Spring java based configuration?
In Spring Java based configuration, you inject all dependencies using java class only. You can use @Configuaration and @Bean annotations to do it.
Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions. Furthermore, @Configuration classes allow inter-bean dependencies to be defined by simply calling other @Bean methods in the same class.
The @Bean annotation is used to indicate that a method instantiates, configures and initializes a new object to be managed by the Spring IoC container. @Bean annotation plays the same role as the <bean/> element.
To enable component scanning, just annotate your @Configuration class as follows:
@Configuration
@ComponentScan(basePackages = "com.howtodoinjava")
public class AppConfig {
...
}
package org.arpit.java2blog.config;
import org.arpit.java2blog.model.Country;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationConfiguration {
@Bean(name="countryObj")
public Country getCountry()
{
return new Country("India");
}
}
Above file is equivalent to below spring configuration xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<bean id="countryObj" class="org.arpit.java2blog.Country" >
<property name="countryName" value="India"/>
</bean>
</beans>
To get above bean to application context, you need to use below code
ApplicationContext appContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
Country countryObj = (Country) appContext.getBean("countryObj");
What is spring annotation based configuration?
You can do dependency injection via annotation also instead of XML configuration. You can define bean autowiring using annotations. You can use @Component,@Repository,@Service and @Controller annotation to configure bean in Spring application.
Annotations wiring is not turned on by default. You need to turn it on using :
<?xml version="1.0" encoding="UTF-8"?>
<bean>
<context:annotation-config/>
</beans>
Once you put above code, you can start using annotation on class , fields or methods.
Few important annotations which you will be using in this type of configuration are :
@Required : The @Required annotation applies to bean property setter methods.
@Autowired : The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.
@Qualifier : The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
JSR-250 Annotations : Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.
Use this for Complete Java Example.
FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
How to create ApplicationContext in a Java Program?
There are following ways to create spring context in a standalone java program.
AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.
FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
What are different bean scopes in Spring?
There are 5 types of bean scopes supported in spring
singleton – Scopes a single bean definition to a single object instance per Spring IoC container(per Application Context).
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request.
session – Return a single bean instance per HTTP session.
globalSession – Return a single bean instance per global HTTP session.
What is default scope of bean in Spring?
singleton is default scope of a bean in Spring. You have to explicitly change scope of a bean if you want different scope.This is one of most asked spring interview questions.
What is ApplicationContext and what are its functions?
ApplicationContext is an central interface for providing configuration information to an application.
An ApplicationContext provides the following functionalities:
Bean factory methods, inherited from ListableBeanFactory. This avoids the need for applications to use singletons.
The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
The ability to publish events. Implementations must provide a means of registering event listeners.
Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.
How do you injection collection in Spring?
You can initialize collection using list and value tag as below:
<bean id="CountryBean" class="org.arpit.java2blog.Country">
<property name="listOfStates">
<list>
<value>Himachal Pradesh</value>
<value>West Bengal</value>
<value>Gujrat</value>
</list>
</property>
</bean>
What do you mean by bean autowiring in Spring?
In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in .The Spring container can autowire relationships between collaborating beans without using and elements which helps cut down on the amount of XML configuration
<bean id="countryBean" class="org.arpit.java2blog.Country" autowire="byName">
difference between dependency injection and autowiring
Dependency Injection is a design pattern, and @autowired is a mechanism for implementing it.
The DI idea is that, instead of your object creating an object it needs (say by using new to instantiate it), this needed object - a dependency - is handed to your object, typically using the constructor or a setter method. If you autowire, you're injecting a dependancy. In this case, Spring uses reflection to make this work, so you're not using the constructor or a setter method, but you're still injecting the dependency.
Error safe autowiring with ‘required=false’
Even if you have used utmost care in autowiring bean dependencies, still you may find strange lookup failures. So, solve this issue, you will need to make autowiring optional so that if no dependency is found, application should not throw any exception and autowiring should simply be ignored.
This can be done in two ways:
If you want to make specific bean autowiring non-mandatory for a specific bean property, use required=”false” attribute in @Autowired annotation.
EmployeeBean.java
@Autowired (required=false)
@Qualifier ("finance")
private DepartmentBean departmentBean;
If you want to apply optional autowiring at global level i.e. for all properties in all beans; use below configuration setting.
beans.xml
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
<property name="requiredParameterValue" value="false" />
</bean>
Difference between @Autowired , @Resource and @Inject annotation in Spring?
@Autowire , @Inject, @Resource they all server the same purpose
The main difference is that, @Autowired and @Inject works similar for 100% without any differentiation.These two annotations using AutowiredAnnotationBeanPostProcessor to inject dependencies. But,@Resource uses CommonAnnotationBeanPostProcessor to inject dependencies and there is difference in the order of checking.
@Autowired and @Inject
Matches by Type
Restricts by Qualifiers
Matches by Name
@Resource
Matches by Name
Matches by Type
Restricts by Qualifiers (ignored if match is found by name)
The @Inject annotation also serves the same purpose, but the main difference between them is that @Inject is a standard annotation for dependency injection and @Autowired is spring specific
Ref: https://javabeat.net/difference-resource-autowired-inject-spring-injection/
@Inject and @Named Annotations Difference
JSR-330 annotations.
@Inject instead of Spring’s @Autowired to inject a bean.
@Named instead of Spring’s @Component to declare a component/bean.(@Component can be referred from my previous post Classpath Scaning)
What are different modes of autowiring supported by Spring?
There are following autowiring modes which can be used to instruct Spring container to use autowiring for dependency injection.
no:
Default, no auto wiring, set it manually via “ref” attribute as we have done in dependency injection via settor method post.
byName:
Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file and it tries to match it with name of bean in xml configuration file.
byType:
Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.
contructor:
byType mode in constructor argument.
autodetect:
Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
@Resource annotation in spring
The @Resource annotation in spring performs the autowiring functionality. This annotation follows the autowire=byName semantics in the XML based configuration i.e. it takes the name attribute for the injection. Below snippet shows how to use this annotation.
What's the difference between @Component, @Repository & @Service annotations in Spring?
From Spring Documentation:
The @Repository annotation is a marker for any class that fulfils the role or stereotype of a repository (also known as Data Access Object or DAO). Among the uses of this marker is the automatic translation of exceptions, as described in Exception Translation.
Spring provides further stereotype annotations: @Component, @Service, and @Controller. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases (in the persistence, service, and presentation layers, respectively). Therefore, you can annotate your component classes with @Component, but, by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects.
For example, these stereotype annotations make ideal targets for pointcuts. @Repository, @Service, and @Controller can also carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated earlier, @Repository is already supported as a marker for automatic exception translation in your persistence layer.
┌──────────────┬─────────────────────────────────────────────────────┐
│ Annotation │ Meaning │
├──────────────┼─────────────────────────────────────────────────────┤
│ @Component │ generic stereotype for any Spring-managed component │
│ @Repository │ stereotype for persistence layer │
│ @Service │ stereotype for service layer │
│ @Controller │ stereotype for presentation layer (spring-mvc) │
└──────────────┴─────────────────────────────────────────────────────┘
Please add difference between @Component,@Repository,@Service and @Controller
ReplyDeleteDone.. Thanks for the suggestion :)
Delete