Skip to main content

Spring


     *********************SPRING Interview Question***************************
Question 1:  What is Spring Framework?
Spring is one of the most widely used Java EE frameworks. Spring framework core concepts are “Dependency Injection” and “Aspect Oriented Programming”.
Spring framework can be used in normal java applications also to achieve loose coupling between different components by implementing dependency injection and we can perform cross cutting tasks such as logging and authentication using spring support for aspect oriented programming.
Question 2:  What are some of the important features and advantages of Spring Framework?
Spring Framework is built on top of two design concepts – Dependency Injection and Aspect Oriented Programming.
Some of the features of spring framework are:
·         Lightweight and very little overhead of using framework for our development.
·         Dependency Injection or Inversion of Control to write components that are independent of each other, spring container takes care of wiring them together to achieve our work.
·         Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
·         Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as well as JSON response.
·         Support for transaction management, JDBC operations, File uploading, Exception Handling etc with very little configurations, either by using annotations or by spring bean configuration file.
Question 3: What do you understand by Dependency Injection?
Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution from compile-time to runtime.
Some of the benefits of using Dependency Injection are: Separation of Concerns, Boilerplate Code reduction, Configurable components and easy unit testing.
Question 4:  How do we implement DI in Spring Framework?
We can use Spring XML based as well as Annotation based configuration to implement DI in spring applications.
Question 5:  Name some of the important Spring Modules?
Some of the important Spring Framework modules are:
Spring Context – for dependency injection.
Spring AOP – for aspect oriented programming.
Spring DAO – for database operations using DAO pattern
Spring JDBC – for JDBC and DataSource support.
Spring ORM – for ORM tools support such as Hibernate
Spring Web Module – for creating web applications.
Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.
Question 6:  What do you understand by Aspect Oriented Programming?
Enterprise applications have some common cross-cutting concerns that is applicable for different types of Objects and application modules, such as logging, transaction management, data validation, authentication etc. In Object Oriented Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different classes methods.
AOP takes out the direct dependency of cross-cutting tasks from classes that is not possible in normal object oriented programming. For example, we can have a separate class for logging but again the classes will have to call these methods for logging the data.
Question 7: What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?
Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal class configured and then configured in Spring Bean configuration file or we can use Spring AspectJ support to declare a class as Aspect using @Aspect annotation.
Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that gets executed when a specific join point with matching pointcut is reached in the application
Pointcut: Pointcut are regular expressions that is matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ pointcut expression language for determining the join points where advice methods will be applied.
Join Point: A join point is the specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join points is always the execution of a method.
Advice Arguments: We can pass arguments in the advice methods. We can use args() expression in the pointcut to be applied to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method from where argument type is determined.
Question 8: What is the difference between Spring AOP and AspectJ AOP?
AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some cases. Main differences between Spring AOP and AspectJ are:
Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all kinds of pointcuts.
One of the shortcoming of Spring AOP is that it can be applied only to the beans created through Spring Context.
Question 9: What is Spring IoC Container?
Inversion of Control (IoC) is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other assembler objects. Spring IoC container is the program that injects dependencies into an object and make it ready for our use.
Spring Framework IoC container classes are part of org.springframework.beans and org.springframework.context packages and provides us different ways to decouple the object dependencies.
Some of the useful ApplicationContext implementations that we use are;
AnnotationConfigApplicationContext: For standalone java applications using annotations based configuration
ClassPathXmlApplicationContext: For standalone java applications using XML based configuration.
FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.
Question 10: What is a Spring Bean?
Any normal java class that is initialized by Spring IoC container is called Spring Bean. We use Spring ApplicationContext to get the Spring Bean instance.
Spring IoC container manages the life cycle of Spring Bean, bean scopes and injecting any required dependencies in the bean.
Question 11: What is the importance of Spring bean configuration file?
We use Spring Bean configuration file to define all the beans that will be initialized by Spring Context. When we create the instance of Spring ApplicationContext, it reads the spring bean xml file and initialize all of them. Once the context is initialized, we can use it to get different bean instances.
Apart from Spring Bean configuration, this file also contains spring MVC interceptors, view resolvers and other elements to support annotations based configurations.
Question 12: What are different scopes of Spring Bean?
There are five scopes defined for Spring Beans.
singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
prototype: A new instance will be created every time the bean is requested.
request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
session: A new bean will be created for each HTTP session by the container.
global-session: This is used to create global session beans for Portlet applications.
Spring Framework is extendable and we can create our own scopes too, however most of the times we are good with the scopes provided by the framework.
To set spring bean scopes we can use “scope” attribute in bean element or @Scope annotation for annotation based configurations.
Question 13: What is Spring Bean life cycle?
Spring Beans are initialized by Spring Container and all the dependencies are also injected. When context is destroyed, it also destroys all the initialized beans. This works well in most of the cases but sometimes we want to initialize other resources or do some validation before making our beans ready to use. Spring framework provides support for post-initialization and pre-destroy methods in spring beans.
We can do this by two ways – by implementing InitializingBean and DisposableBean interfaces or using init-method and destroy-method attribute in spring bean configurations.
Question 14:  How to get ServletContext and ServletConfig object in a Spring Bean?
There are two ways to get Container specific objects in the spring bean.
1. Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete example of these aware interfaces.
2. Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only though.
@Autowired
ServletContext servletContext;
Question 15: What is Bean wiring and @Autowired annotation?
The process of injection spring bean dependencies while initializing it called Spring Bean Wiring.
Usually it’s best practice to do the explicit wiring of all the bean dependencies, but spring framework also supports autowiring. We can use @Autowired annotation with fields or methods for autowiring byType. For this annotation to work, we also need to enable annotation based configuration in spring bean configuration file. This can be done by context:annotation-config element.
Question 16: What are different types of Spring Bean autowiring?
There are four types of autowiring in Spring framework.
autowire byName
autowire byType
autowire by constructor
autowiring by @Autowired and @Qualifier annotations
Prior to Spring 3.1, autowire by autodetect was also supported that was similar to autowire by constructor or byType.
Question 17: Does Spring Bean provide thread safety?
The default scope of Spring bean is singleton, so there will be only one instance per context. That means that all the having a class level variable that any thread can update will lead to inconsistent data. Hence in default mode spring beans are not thread-safe.
However we can change spring bean scope to request, prototype or session to achieve thread-safety at the cost of performance. It’s a design decision and based on the project requirements.
Question 18: What is a Controller in Spring MVC?
Just like MVC design pattern, Controller is the class that takes care of all the client requests and send them to the configured resources to handle it. In Spring MVC, org.springframework.web.servlet.DispatcherServlet is the front controller class that initializes the context based on the spring beans configurations.
A Controller class is responsible to handle different kind of client requests based on the request mappings. We can create a controller class by using @Controller annotation. Usually it’s used with @RequestMappingannotation to define handler methods for specific URI mapping.
Question 19: What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?
@Component is used to indicate that a class is a component. These classes are used for auto detection and configured as bean, when annotation based configurations are used.
@Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.
@Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.
@Service is used to indicate that a class is a Service. Usually the business facade classes that provide some services are annotated with this.
We can use any of the above annotations for a class for auto-detection but different types are provided so that you can easily distinguish the purpose of the annotated classes.
Question 20: What is DispatcherServlet and ContextLoaderListener?
DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.
ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.
Question 21: 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.
Question 22: What are the minimum configurations needed to create Spring MVC application?
For creating a simple Spring MVC application, we would need to do following tasks.
·         Add spring-context and spring-webmvc dependencies in the project.
·         Configure DispatcherServlet in the web.xml file to handle requests through spring container.
·         Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also we need to configure view resolver for view pages.
·         Controller class with request mappings defined to handle the client requests.
·         Above steps should be enough to create a simple Spring MVC Hello World application.
Question 23: How would you relate Spring MVC Framework to MVC architecture?
As the name suggests Spring MVC is built on top of Model-View-Controller architecture. DispatcherServlet is the Front Controller in the Spring MVC application that takes care of all the incoming requests and delegate it to different controller handler methods.
Model can be any Java Bean in the Spring Framework, just like any other MVC framework Spring provides automatic binding of form data to java beans. We can set model beans as attributes to be used in the view pages.
View Pages can be JSP, static HTMLs etc. and view resolvers are responsible for finding the correct view page. Once the view page is identified, control is given back to the DispatcherServlet controller. DispatcherServlet is responsible for rendering the view and returning the final response to the client.
Question 24: What are some of the important Spring annotations you have used?
Some of the Spring annotations that I have used in my project are:
@Controller – for controller classes in Spring MVC project.
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation.
@ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
@Autowired – for autowiring dependencies in spring beans.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
@Service – for service classes.
@Scope – for configuring scope of the spring bean.
@Configuration, @ComponentScan and @Bean – for java based configurations.
AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcutetc.
Question 25: How would you achieve Transaction Management in Spring?
Spring framework provides transaction management support through Declarative Transaction Management as well as programmatic transaction management. Declarative transaction management is most widely used because it’s easy to use and works in most of the cases.
We use annotate a method with @Transactional annotation for Declarative transaction management. We need to configure transaction manager for the DataSource in the spring bean configuration file.
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>




What is IOC (inversion of control) Container ?
Ioc is a principle or paradigm. we have some set of rules or guidelines to develop a application in a decouple manner.
Ioc is a collabrating the object and managing the lifecycle of those objects is called ioc container.
Ioc container says that you don't bother about object creation or you don't create your objects only describe how they should be created i will manage it.
The basic concept of the Dependency Injection or Inversion of Control is that, programmer do not need to create the objects, instead just describe how it should be created.
Benefits of Ioc:
--------------------
Minimize the code in our application.
It provides loose coupling between components in our application.
If any modification have to do then it doesnt effect other components.
It supports eager instantiation and lazy instantiation of services.
Enhancement will be easy.
2. What is dependency injection? Types of dependency injection?
Dependency injection is a software design pattern that deals with how components are organizing their dependencies.
It is the process of injecting the dependencies in dependent class automatically. We no need to create obj and no need to map with obj.
Dependency Injection means injecting the dependency between two object as per as our requirement in our application, this help to reducing the dependency to each other.
Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application.
Dependency Injection makes our programming code loosely coupled
It is internally follow strategy design pattern means favour composition over inheritance.
Always design to interface never code to implementation.
3. Difference between setter injection and constructor injection?
Setter Injection:
To perform setter injection we will use <property> tag.
Partial dependencies is possible. means if we have 3 dependencies like int, long, String it is not necessary to inject all values.
If we have more dependencies eg 15 to 20 are there in our bean class then in this case setter injection is not recomonded to use as we need to write almost 20 setters right bean lenght will be increased.
Setter injection makes bean class object as mutable( we can change).
Setter injection support cyclic dependencies.
Constructor injection:
To perform constructor injection <constructor-arg> tag is required.
Partial injection of dependencies cannot be possible because for calling a constructor we must pass all the arguments.
if we have more dependencies in this case constructor injection is highly recomonded to use because we can inject all the dependencies with in the 3 to 4 lines (by calling one constructor).
Constructor injection makes bean class obj is immutable( we cannot change).
Constructor injection doesn't support cyclic dependencies.
4. Difference between BeanFactory and ApplicationContext?
BeanFactory:
BeanFactory is a basic container. it can only manage a bean life cycle. but it can not provide service like transaction, security etc.
If we developing small scale application like mobile application embeded system then we use beanfactory.
Beanfactory is lazy initializer. beanfactory container will not create a bean obj upto the request time.
Beanfactory container supports only two scope(singeltone & prototype).
Beanfactory doesnt support internationalization, event handling, event processing.
Application Context:
ApplicationContext is a advanced container it manage bean life cycle and also provide transaction security etc.
If we are developing enterprise application like(web application, distributed application) then ApplicationContext is recomended to use.
ApplicationContext container creates bean object of singelton bean at the time of loading only.it is eager initialzer.
ApplicationContext container support all the bean scope (singletone,prototype, session,request).
It supports internationalization, event handling, event processing also.
5. What is bean autowiring and types of autowire modes?
Injecting the dependencies between the obj is called wiring.
Instead of telling the spring to manage the dependency by writting <property> or <constructor> tag in spring bean configuration file.
If we instruct the spring to automatically detect the dependencies and perform the injection between them it is called bean autowiring.
It is used only when rapid application development is required.
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">
Modes of Autowire:
1. Autowire= "byname"
If u enable autowiring byname, spring will inject the bean based on property name. it uses setter method.
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.
2. Autowire= "bytype"
If u enable autowire bytype, spring will inject the beans based on the property type. it uses setter method.
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
3. Autowire= "byconstructor"
If u enable autowire byconstructor, spring will injects the beans uses constructor.
byType mode in constructor argument.
4. Autowire="byautodetect"
Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
6. What is bean scope? and types of bean scope. Difference between singleton and prototype bean scope?
Beanscope is a concept which is provided by spring people. in spring when u declare a class as a bean by default the bean will be created under the singleton scope.
Types of beanscope:
1. Singleton
bydefault every bean declared in the configuration file is singleton.
Scopes a single bean definition to a single object instance per Spring IOC container.
Singleton is default scope of a bean in Spring. You have to explicitly change scope of a bean if you want different scope.
If bean scope is singleton then Ioc container creates the bean class obj and keeps in the HashMap element as value by having bean 'id' as key and uses that obj across the multiple "factory.getBean() method.
2. Prototype
Prototype – Return a new bean instance each time when requested.
When we declare a bean scope as a prototype then Ioc container doesn't keep the created bean class object in HashMap so it returns new obj for every factory.getBean().
3. Request
Request – Return a single bean instance per HTTP request.
When we declare a bean scope as request ,for every Http request new bean instance will be injected.
4. Session
Session – Return a single bean instance per HTTP session.
For every new Http session ,new bean instance will be injected.
5. Global session
The global session scope is deprecated in the market from spring 3.0.
Return a single bean instance per global HTTP session.
7. what is bean life cycle?
-------------------------------------------
-> every obj in this world have life cycle. whatever the obj is performing after the birth and before the death is known as life cycle of the obj.
-> the spring container find the beans defination from the xml file and instantiate the bean .
-> using dependency injection spring populates all of the properties as specified in the bean defination.
-> in servlet life cycle we are used following life cycle methods . 1> init() 2> service() 3> destroy().
-> spring bean allows two life cycle methods. 1> init() 2> destroy().
Spring AOP:
1. What is Aop ? What is the principles of Aop? and where we apply Aop in projects?
Aop is not a programming language. it is a methodlogy or principles like oops. we have some set of rules or guidelines to make our application in decouple manner.
Aop is the process of separating the primary logic from the secondry logic (crosscutting logic).
in every application there will be two types of logic, one is called primary buisness logic and other one is helper logic which makes your primary buisness logic work better.
In the enterprise level application we used to add diff crosscutting functionlaties (means adding diff types of services to the application at runtime).


Core Spring Framework Annotations
@Required
This annotation is applied on bean setter methods. Consider a scenario where you need to enforce a required property. The @Required annotation indicates that the affected bean must be populated at configuration time with the required property. Otherwise an exception of type BeanInitializationException is thrown.
@Autowired
This annotation is applied on fields, setter methods, and constructors. The @Autowired annotation injects object dependency implicitly.
When you use @Autowired on fields and pass the values for the fields using the property name, Spring will automatically assign the fields with the passed values.
You can even use @Autowired  on private properties, as shown below. (This is a very poor practice though!)
1
2
3
4
5
public class Customer {
    @Autowired                              
    private Person person;                  
    private int type;
}
When you use @Autowired on setter methods, Spring tries to perform the by Type autowiring on the method. You are instructing Spring that it should initiate this property using setter method where you can add your custom code, like initializing any other property with this property.
1
2
3
4
5
6
7
public class Customer {                                                                                        
    private Person person;
    @Autowired                                                                                                      
    public void setPerson (Person person) {
     this.person=person;
    }
}
Consider a scenario where you need instance of class A, but you do not store A in the field of the class. You just use A to obtain instance of B, and you are storing B in this field. In this case setter method autowiring will better suite you. You will not have class level unused fields.
When you use @Autowired on a constructor, constructor injection happens at the time of object creation. It indicates the constructor to autowire when used as a bean. One thing to note here is that only one constructor of any bean class can carry the @Autowired annotation.
1
2
3
4
5
6
7
8
@Component
public class Customer {
    private Person person;
    @Autowired
    public Customer (Person person) {
      this.person=person;
    }
}
NOTE: As of Spring 4.3, @Autowired  became optional on classes with a single constructor. In the above example, Spring would still inject an instance of the Person  class if you omitted the @Autowired  annotation.
@Qualifier
This annotation is used along with @Autowired annotation. When you need more control of the dependency injection process, @Qualifier can be used. @Qualifier can be specified on individual constructor arguments or method parameters. This annotation is used to avoid confusion which occurs when you create more than one bean of the same type and want to wire only one of them with a property.
Consider an example where an interface BeanInterface is implemented by two beans BeanB1 and BeanB2.
1
2
3
4
5
6
7
8
@Component
public class BeanB1 implements BeanInterface {
  //
}
@Component
public class BeanB2 implements BeanInterface {
  //
}
Now if BeanA autowires this interface, Spring will not know which one of the two implementations to inject.
One solution to this problem is the use of the 
@Qualifier annotation.
1
2
3
4
5
6
7
@Component
public class BeanA {
  @Autowired
  @Qualifier("beanB2")
  private BeanInterface dependency;
  ...
}
With the @Qualifier annotation added, Spring will now know which bean to autowire where beanB2 is the name of BeanB2.
Description: Spring Framework 5Learn the Spring Framework with my Spring Framework 5 – Beginner to Guru Course!
@Configuration
This annotation is used on classes which define beans. @Configuration is an analog for XML configuration file – it is configuration using Java class. Java class annotated with @Configuration is a configuration by itself and will have methods to instantiate and configure the dependencies.
Here is an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
public class DataConfig{
  @Bean
  public DataSource source(){
    DataSource source = new OracleDataSource();
    source.setURL();
    source.setUser();
    return source;
  }
  @Bean
  public PlatformTransactionManager manager(){
    PlatformTransactionManager manager = new BasicDataSourceTransactionManager();
    manager.setDataSource(source());
    return manager;
  }
}
@ComponentScan
This annotation is used with @Configuration annotation to allow Spring to know the packages to scan for annotated components. @ComponentScan is also used to specify base packages using basePackageClasses orbasePackage attributes to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
Checkout this post for an in depth look at the Component Scan annotation.
@Bean
This annotation is used at the method level. @Bean annotation works with @Configuration to create Spring beans. As mentioned earlier, @Configuration will have methods to instantiate and configure dependencies. Such methods will be annotated with @Bean. The method annotated with this annotation works as bean ID and it creates and returns the actual bean.
Here is an example:
1
2
3
4
5
6
7
8
9
10
11
@Configuration
public class AppConfig{
  @Bean
  public Person person(){
    return new Person(address());
  }
  @Bean
  public Address address(){
    return new Address();
  }
}
@Lazy
This annotation is used on component classes. By default all autowired dependencies are created and configured at startup. But if you want to initialize a bean lazily, you can use @Lazy annotation over the class. This means that the bean will be created and initialized only when it is first requested for. You can also use this annotation on @Configuration classes. This indicates that all @Bean methods within that @Configuration should be lazily initialized.
@Value
This annotation is used at the field, constructor parameter, and method parameter level. The @Value annotation indicates a default value expression for the field or parameter to initialize the property with. As the @Autowiredannotation tells Spring to inject object into another when it loads your application context, you can also use@Value annotation to inject values from a property file into a bean’s attribute. It supports both #{...} and${...} placeholders.
Spring Framework Stereotype Annotations
@Component
This annotation is used on classes to indicate a Spring component. The @Component annotation marks the Java class as a bean or say component so that the component-scanning mechanism of Spring can add into the application context.
@Controller
The @Controller  annotation is used to indicate the class is a Spring controller. This annotation can be used to identify controllers for Spring MVC or Spring WebFlux.
@Service
This annotation is used on a class. The @Service marks a Java class that performs some service, such as execute business logic, perform calculations and call external APIs. This annotation is a specialized form of the@Component annotation intended to be used in the service layer.
@Repository
This annotation is used on Java classes which directly access the database. The @Repository annotation works as marker for any class that fulfills the role of repository or Data Access Object.
This annotation has a automatic translation feature. For example, when an exception occurs in the @Repositorythere is a handler for that exception and there is no need to add a try catch block.
Spring Boot Annotations
@EnableAutoConfiguration
This annotation is usually placed on the main application class. The @EnableAutoConfiguration annotation implicitly defines a base “search package”. This annotation tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
@SpringBootApplication
This annotation is used on the application class while setting up a Spring Boot project. The class that is annotated with the @SpringBootApplication must be kept in the base package. The one thing that the@SpringBootApplication does is a component scan. But it will scan only its sub-packages. As an example, if you put the class annotated with @SpringBootApplication in com.example then @SpringBootApplication will scan all its sub-packages, such as com.example.acom.example.b, and com.example.a.x.
The @SpringBootApplication is a convenient annotation that adds all the following:
·         @Configuration
·         @EnableAutoConfiguration
·         @ComponentScan
Spring MVC and REST Annotations
@Controller
This annotation is used on Java classes that play the role of controller in your application. The @Controllerannotation allows autodetection of component classes in the classpath and auto-registering bean definitions for them. To enable autodetection of such annotated controllers, you can add component scanning to your configuration. The Java class annotated with @Controller is capable of handling multiple request mappings.
This annotation can be used with Spring MVC and Spring WebFlux.
@RequestMapping
This annotation is used both at class and method level. The @RequestMapping annotation is used to map web requests onto specific handler classes and handler methods. When @RequestMapping is used on class level it creates a base URI for which the controller will be used. When this annotation is used on methods it will give you the URI on which the handler methods will be executed. From this you can infer that the class level request mapping will remain the same whereas each handler method will have their own request mapping.
Sometimes you may want to perform different operations based on the HTTP method used, even though the request URI may remain the same. In such situations, you can use the method attribute of @RequestMapping with an HTTP method value to narrow down the HTTP methods in order to invoke the methods of your class.
Here is a basic example on how a controller along with request mappings work:
1
2
3
4
5
6
7
8
@Controller
@RequestMapping("/welcome")
public class WelcomeController{
  @RequestMapping(method = RequestMethod.GET)
  public String welcomeAll(){
    return "welcome all";
  }
}
In this example only GET requests to /welcome is handled by the welcomeAll() method.
This annotation also can be used with Spring MVC and Spring WebFlux.
The @RequestMapping  annotation is very versatile. Please see my in depth post on Request Mapping bere.
@CookieValue
This annotation is used at method parameter level. @CookieValue is used as argument of request mapping method. The HTTP cookie is bound to the @CookieValue parameter for a given cookie name. This annotation is used in the method annotated with @RequestMapping.
Let us consider that the following cookie value is received with a http request:
JSESSIONID=418AB76CD83EF94U85YD34W
To get the value of the cookie, use @CookieValue like this:
1
2
3
@RequestMapping("/cookieValue")
  public void getCookieValue(@CookieValue "JSESSIONID" String cookie){
}
@CrossOrigin
This annotation is used both at class and method level to enable cross origin requests. In many cases the host that serves JavaScript will be different from the host that serves the data. In such a case Cross Origin Resource Sharing (CORS) enables cross-domain communication. To enable this communication you just need to add the@CrossOrigin annotation.
By default the @CrossOrigin annotation allows all origin, all headers, the HTTP methods specified in the@RequestMapping annotation and maxAge of 30 min. You can customize the behavior by specifying the corresponding attribute values.
An example to use @CrossOrigin at both controller and handler method levels is this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

@CrossOrigin(origins = "http://example.com")
@RequestMapping("/message")
  public Message getMessage() {
      // ...
    }

@RequestMapping("/note")
    public Note getNote() {
        // ...
    }
}
In this example, both getExample() and getNote() methods will have a maxAge of 3600 seconds. Also,getExample() will only allow cross-origin requests from http://example.com, while getNote() will allow cross-origin requests from all hosts.
Composed @RequestMapping Variants
Spring framework 4.3 introduced the following method-level variants of @RequestMapping annotation to better express the semantics of the annotated methods. Using these annotations have become the standard ways of defining the endpoints. They act as wrapper to @RequestMapping.
These annotations can be used with Spring MVC and Spring WebFlux.
@GetMapping
This annotation is used for mapping HTTP GET requests onto specific handler methods. @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)
@PostMapping
This annotation is used for mapping HTTP POST requests onto specific handler methods. @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST)
@PutMapping
This annotation is used for mapping HTTP PUT requests onto specific handler methods. @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT)
@PatchMapping
This annotation is used for mapping HTTP PATCH requests onto specific handler methods. @PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH)
@DeleteMapping
This annotation is used for mapping HTTP DELETE requests onto specific handler methods. @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE)
@ExceptionHandler
This annotation is used at method levels to handle exception at the controller level. The @ExceptionHandlerannotation is used to define the class of exception it will catch. You can use this annotation on methods that should be invoked to handle an exception. The @ExceptionHandler values can be set to an array of Exception types. If an exception is thrown that matches one of the types in the list, then the method annotated with matching @ExceptionHandler will be invoked.
@InitBinder
This annotation is a method level annotation that plays the role of identifying the methods which initialize theWebDataBinder - a DataBinder that binds the request parameter to JavaBean objects. To customise request parameter data binding , you can use @InitBinder annotated methods within our controller. The methods annotated with @InitBinder all argument types that handler methods support.
The 
@InitBinder annotated methods will get called for each HTTP request if you don’t specify the value element of this annotation. The value element can be a single or multiple form names or request parameters that the init binder method is applied to.
@Mappings and @Mapping
This annotation is used on fields. The @Mapping annotation is a meta annotation that indicates a web mapping annotation. When mapping different field names, you need to configure the source field to its target field and to do that you have to add the @Mappings annotation. This annotation accepts an array of @Mapping having the source and the target fields.
@MatrixVariable
This annotation is used to annotate request handler method arguments so that Spring can inject the relevant bits of matrix URI. Matrix variables can appear on any segment each separated by a semicolon. If a URL contains matrix variables, the request mapping pattern must represent them with a URI template. The@MatrixVariable annotation ensures that the request is matched with the correct matrix variables of the URI.
@PathVariable
This annotation is used to annotate request handler method arguments. The @RequestMapping annotation can be used to handle dynamic changes in the URI where certain URI value acts as a parameter. You can specify this parameter using a regular expression. The @PathVariable annotation can be used declare this parameter.
@RequestAttribute
This annotation is used to bind the request attribute to a handler method parameter. Spring retrieves the named attributes value to populate the parameter annotated with @RequestAttribute. While the @RequestParamannotation is used bind the parameter values from query string, the @RequestAttribute is used to access the objects which have been populated on the server side.
@RequestBody
This annotation is used to annotate request handler method arguments. The @RequestBody annotation indicates that a method parameter should be bound to the value of the HTTP request body. The HttpMessageConveter is responsible for converting from the HTTP request message to object.
@RequestHeader
This annotation is used to annotate request handler method arguments. The @RequestHeader annotation is used to map controller parameter to request header value. When Spring maps the request, @RequestHeader checks the header with the name specified within the annotation and binds its value to the handler method parameter. This annotation helps you to get the header details within the controller class.
@RequestParam
This annotation is used to annotate request handler method arguments. Sometimes you get the parameters in the request URL, mostly in GET requests. In that case, along with the @RequestMapping annotation you can use the @RequestParam annotation to retrieve the URL parameter and map it to the method argument. The@RequestParam annotation is used to bind request parameters to a method parameter in your controller.
@RequestPart
This annotation is used to annotate request handler method arguments. The @RequestPart annotation can be used instead of @RequestParam to get the content of a specific multipart and bind to the method argument annotated with @RequestPart. This annotation takes into consideration the “Content-Type” header in the multipart(request part).
@ResponseBody
This annotation is used to annotate request handler methods. The @ResponseBody annotation is similar to the@RequestBody annotation. The @ResponseBody annotation indicates that the result type should be written straight in the response body in whatever format you specify like JSON or XML. Spring converts the returned object into a response body by using the HttpMessageConveter.
@ResponseStatus
This annotation is used on methods and exception classes. @ResponseStatus marks a method or exception class with a status code and a reason that must be returned. When the handler method is invoked the status code is set to the HTTP response which overrides the status information provided by any other means. A controller class can also be annotated with @ResponseStatus which is then inherited by all @RequestMapping methods.
@ControllerAdvice
This annotation is applied at the class level. As explained earlier, for each controller you can use@ExceptionHandler on a method that will be called when a given exception occurs. But this handles only those exception that occur within the controller in which it is defined. To overcome this problem you can now use the@ControllerAdvice annotation. This annotation is used to define @ExceptionHandler@InitBinder and@ModelAttribute methods that apply to all @RequestMapping methods. Thus if you define the @ExceptionHandlerannotation on a method in @ControllerAdvice class, it will be applied to all the controllers.
@RestController
This annotation is used at the class level. The @RestController annotation marks the class as a controller where every method returns a domain object instead of a view. By annotating a class with this annotation you no longer need to add @ResponseBody to all the RequestMapping method. It means that you no more use view-resolvers or send html in response. You just send the domain object as HTTP response in the format that is understood by the consumers like JSON.
@RestController  is a convenience annotation which combines @Controller  and @ResponseBody .
@RestControllerAdvice
This annotation is applied on Java classes. @RestControllerAdvice is a convenience annotation which combines @ControllerAdvice and @ResponseBody. This annotation is used along with the @ExceptionHandler annotation to handle exceptions that occur within the controller.
@SessionAttribute
This annotation is used at method parameter level. The @SessionAttribute annotation is used to bind the method parameter to a session attribute. This annotation provides a convenient access to the existing or permanent session attributes.
@SessionAttributes
This annotation is applied at type level for a specific handler. The @SessionAtrributes annotation is used when you want to add a JavaBean object into a session. This is used when you want to keep the object in session for short lived. @SessionAttributes is used in conjunction with @ModelAttribute.
Consider this example.
1
2
3
4
5
6
@ModelAttribute("person")
public Person getPerson(){}
// within the same controller as above snippet
@Controller
@SeesionAttributes(value="person", types={Person.class})
public class PersonController{}
The @ModelAttribute name is assigned to the @SessionAttributes as value. The @SessionAttributes has two elements. The value element is the name of the session in the model and the types element is the type of session attributes in the model.
Spring Cloud Annotations
@EnableConfigServer
This annotation is used at the class level. When developing a project with a number of services, you need to have a centralized and straightforward manner to configure and retrieve the configurations about all the services that you are going to develop. One advantage of using a centralized config server is that you don’t need to carry the burden of remembering where each configuration is distributed across multiple and distributed components.
You can use Spring cloud’s @EnableConfigServer annotation to start a config server that the other applications can talk to.
@EnableEurekaServer
This annotation is applied to Java classes. One problem that you may encounter while decomposing your application into microservices is that, it becomes difficult for every service to know the address of every other service it depends on. There comes the discovery service which is responsible for tracking the locations of all other microservices.
Netflix’s Eureka is an implementation of a discovery server and integration is provided by Spring Boot. Spring Boot has made it easy to design a Eureka Server by just annotating the entry class with 
@EnableEurekaServer.
@EnableDiscoveryClient
This annotation is applied to Java classes. In order to tell any application to register itself with Eureka you just need to add the @EnableDiscoveryClientannotation to the application entry point. The application that’s now registered with Eureka uses the Spring Cloud Discovery Client abstraction to interrogate the registry for its own host and port.
@EnableCircuitBreaker
This annotation is applied on Java classes that can act as the circuit breaker. The circuit breaker pattern can allow a micro service continue working when a related service fails, preventing the failure from cascading. This also gives the failed service a time to recover.
The class annotated with @EnableCircuitBreaker will monitor, open, and close the circuit breaker.
@HystrixCommand
This annotation is used at the method level. Netflix’s Hystrix library provides the implementation of Circuit Breaker pattern. When you apply the circuit breaker to a method, Hystrix watches for the failures of the method. Once failures build up to a threshold, Hystrix opens the circuit so that the subsequent calls also fail. Now Hystrix redirects calls to the method and they are passed to the specified fallback methods.
Hystrix looks for any method annotated with the 
@HystrixCommand annotation and wraps it into a proxy connected to a circuit breaker so that Hystrix can monitor it.
Consider the following example:
1
2
3
4
5
6
7
8
9
10
11
12
13
@Service
public class BookService{
    private final RestTemplate restTemplate;
    public BookService(RestTemplate rest){
      this.restTemplate =   rest;
    }                                          
  @HystrixCommand(fallbackMethod = "newList")                                                                     public String bookList(){
    URI uri = URI.create("http://localhost:8081/recommended");                                                      return this.restTemplate.getForObject(uri, String.class);  
  }
  public String newList(){
    return "Cloud native Java";
  }
}
Here @HystrixCommand is applied to the original method bookList(). The @HystrixCommand annotation has newList as the fallback method. So for some reason if Hystrix opens the circuit on bookList(), you will have a placeholder book list ready for the users.
Description: Spring Framework 5Learn Spring Framework 5 with my Spring Framework 5: Beginner to Guru course!
Spring Framework DataAccess Annotations
@Transactional
This annotation is placed before an interface definition, a method on an interface, a class definition, or a public method on a class. The mere presence of @Transactional is not enough to activate the transactional behaviour. The @Transactional is simply a metadata that can be consumed by some runtime infrastructure. This infrastructure uses the metadata to configure the appropriate beans with transactional behaviour.
The annotation further supports configuration like:
·         The Propagation type of the transaction
·         The Isolation level of the transaction
·         A timeout for the operation wrapped by the transaction
·         A read only flag - a hint for the persistence provider that the transaction must be read only
The rollback rules for the transaction
Cache-Based Annotations
@Cacheable
This annotation is used on methods. The simplest way of enabling the cache behaviour for a method is to annotate it with @Cacheable and parameterize it with the name of the cache where the results would be stored.
1
2
@Cacheable("addresses")
public String getAddress(Book book){...}
In the snippet above , the method getAddress is associated with the cache named addresses. Each time the method is called, the cache is checked to see whether the invocation has been already executed and does not have to be repeated.
@CachePut
This annotation is used on methods. Whenever you need to update the cache without interfering the method execution, you can use the @CachePut annotation. That is, the method will always be executed and the result cached.
1
2
@CachePut("addresses")
public String getAddress(Book book){...}
Using @CachePut and @Cacheable on the same method is strongly discouraged as the former forces the execution in order to execute a cache update, the latter causes the method execution to be skipped by using the cache.
@CacheEvict
This annotation is used on methods. It is not that you always want to populate the cache with more and more data. Sometimes you may want remove some cache data so that you can populate the cache with some fresh values. In such a case use the @CacheEvict annotation.
1
2
@CacheEvict(value="addresses", allEntries="true")
public String getAddress(Book book){...}
Here an additional element allEntries is used along with the cache name to be emptied. It is set to true so that it clears all values and prepares to hold new data.
@CacheConfig
This annotation is a class level annotation. The @CacheConfig annotation helps to streamline some of the cache information at one place. Placing this annotation on a class does not turn on any caching operation. This allows you to store the cache configuration at the class level so that you don’t have declare things multiple times.
Task Execution and Scheduling Annotations
@Scheduled
This annotation is a method level annotation. The @Scheduled annotation is used on methods along with the trigger metadata. A method with @Scheduled should have void return type and should not accept any parameters.
There are different ways of using the @Scheduled annotation:
1
2
3
4
@Scheduled(fixedDelay=5000)
public void doSomething() {
  // something that should execute periodically  
}
In this case, the duration between the end of last execution and the start of next execution is fixed. The tasks always wait until the previous one is finished.
1
2
3
4
@Scheduled(fixedRate=5000)
public void doSomething() {
  // something that should execute periodically
}
In this case, the beginning of the task execution does not wait for the completion of the previous execution.
1
2
3
4
@Scheduled(initialDelay=1000,fixedRate=5000)
public void doSomething() {
 // something that should execute periodically after an initial delay  
}
The task gets executed initially with a delay and then continues with the specified fixed rate.
@Async
This annotation is used on methods to execute each method in a separate thread. The @Async annotation is provided on a method so that the invocation of that method will occur asynchronously. Unlike methods annotated with @Scheduled, the methods annotated with @Asynccan take arguments. They will be invoked in the normal way by callers at runtime rather than by a scheduled task.
@Async can be used with both void return type methods and the methods that return a value. However methods with return value must have a Future typed return values.
Spring Framework Testing Annotations
@BootstrapWith
This annotation is a class level annotation. The @BootstrapWith annotation is used to configure how the Spring TestContext Framework is bootstrapped. This annotation is used as a metadata to create custom composed annotations and reduce the configuration duplication in a test suite.
@ContextConfiguration
This annotation is a class level annotation that defines a metadata used to determine which configuration files to use to the load the ApplicationContext for your test. More specifically @ContextConfiguration declares the annotated classes that will be used to load the context. You can also tell Spring where to locate for the file.
@ContextConfiguration(locations={"example/test-context.xml", loader = Custom ContextLoader.class})
@WebAppConfiguration
This annotation is a class level annotation. The @WebAppConfiguration is used to declare that theApplicationContext loaded for an integration test should be a WebApplicationContext. This annotation is used to create the web version of the application context. It is important to note that this annotation must be used with the @ContextConfiguration annotation.The default path to the root of the web application is src/main/webapp.You can override it by passing a different path to the <span class="theme:classic lang:default decode:true crayon-inline">@WebAppConfiguration.
@Timed
This annotation is used on methods. The @Timed annotation indicates that the annotated test method must finish its execution at the specified time period(in milliseconds). If the execution exceeds the specified time in the annotation, the test fails.
1
2
@Timed(millis=10000)
public void testLongRunningProcess() {  ... }
In this example, the test will fail if it exceeds 10 seconds of execution.
@Repeat
This annotation is used on test methods. If you want to run a test method several times in a row automatically, you can use the @Repeat annotation. The number of times that test method is to be executed is specified in the annotation.
1
2
3
@Repeat(10)
@Test
public void testProcessRepeatedly() {  ... }
In this example, the test will be executed 10 times.
@Commit
This annotation can be used as both class-level or method-level annotation. After execution of a test method, the transaction of the transactional test method can be committed using the @Commit annotation. This annotation explicitly conveys the intent of the code. When used at the class level, this annotation defines the commit for all test methods within the class. When declared as a method level annotation @Commit specifies the commit for specific test methods overriding the class level commit.
@RollBack
This annotation can be used as both class-level and method-level annotation. The @RollBack annotation indicates whether the transaction of a transactional test method must be rolled back after the test completes its execution. If this true @Rollback(true), the transaction is rolled back. Otherwise, the transaction is committed.@Commit is used instead of @RollBack(false).
When used at the class level, this annotation defines the rollback for all test methods within the class.
When declared as a method level annotation @RollBack specifies the rollback for specific test methods overriding the class level rollback semantics.
@DirtiesContext
This annotation is used as both class-level and method-level annotation. @DirtiesContext indicates that the Spring ApplicationContext has been modified or corrupted in some manner and it should be closed. This will trigger the context reloading before execution of next test. The ApplicationContext is marked as dirty before or after any such annotated method as well as before or after current test class.
The @DirtiesContext annotation supports BEFORE_METHODBEFORE_CLASS, and BEFORE_EACH_TEST_METHOD modes for closing the ApplicationContext before a test.
NOTE: Avoid overusing this annotation. It is an expensive operation and if abused, it can really slow down your test suite.
@BeforeTransaction
This annotation is used to annotate void methods in the test class. @BeforeTransaction annotated methods indicate that they should be executed before any transaction starts executing. That means the method annotated with @BeforeTransaction must be executed before any method annotated with @Transactional.
@AfterTransaction
This annotation is used to annotate void methods in the test class. @AfterTransaction annotated methods indicate that they should be executed after a transaction ends for test methods. That means the method annotated with @AfterTransaction must be executed after the method annotated with @Transactional.
@Sql
This annotation can be declared on a test class or test method to run SQL scripts against a database. The @Sqlannotation configures the resource path to SQL scripts that should be executed against a given database either before or after an integration test method. When @Sql is used at the method level it will override any @Sqldefined in at class level.
@SqlConfig
This annotation is used along with the @Sql annotation. The @SqlConfig annotation defines the metadata that is used to determine how to parse and execute SQL scripts configured via the @Sql annotation. When used at the class-level, this annotation serves as global configuration for all SQL scripts within the test class. But when used directly with the config attribute of @Sql@SqlConfig serves as a local configuration for SQL scripts declared.
@SqlGroup
This annotation is used on methods. The @SqlGroup annotation is a container annotation that can hold several@Sql annotations. This annotation can declare nested @Sql annotations.
In addition, 
@SqlGroup is used as a meta-annotation to create custom composed annotations. This annotation can also be used along with repeatable annotations, where @Sql can be declared several times on the same method or class.
@SpringBootTest
This annotation is used to start the Spring context for integration tests. This will bring up the full autoconfigruation context.
@DataJpaTest
The @DataJpaTest  annotation will only provide the autoconfiguration required to test Spring Data JPA using an in-memory database such as H2.
This annotation is used instead of @SpringBootTest
@DataMongoTest
The @DataMongoTest  will provide a minimal autoconfiguration and an embedded MongoDB for running integration tests with Spring Data MongoDB.
@WebMVCTest
The @WebMVCTest will bring up a mock servlet context for testing the MVC layer. Services and components are not loaded into the context. To provide these dependencies for testing, the @MockBean annotation is typically used.
@AutoConfigureMockMVC
The @AutoConfigureMockMVC  annotation works very similar to the @WebMVCTest  annotation, but the full Spring Boot context is started.
@MockBean
Creates and injects a Mockito Mock for the given dependency.
@JsonTest
Will limit the auto configuration of Spring Boot to components relevant to processing JSON.
This annotation will also autoconfigure an instance of JacksonTester or GsonTester.
@TestPropertySource
Class level annotation used to specify property sources for the test class.



Comments

Popular posts from this blog

Mockito interview Questions

1.       Question 1. What Is Mockito? Answer : Mockito allows creation of mock object for the purpose of Test Driven Development and Behavior Driven development. Unlike creating actual object, Mockito allows creation of fake object (external dependencies) which allows it to give consistent results to a given invocation. 2.       Question 2. Why Do We Need Mockito? What Are The Advantages? Answer : Mockito differentiates itself from the other testing framework by removing the expectation beforehand. So, by doing this, it reduces the coupling. Most of the testing framework works on the "expect-run-verify". Mockito allows it to make it "run-verify" framework. Mockito also provides annotation which allows to reduce the boilerplate code. 3.       Question 3. Can You Explain A Mockito Framework? Answer : In Mockito, you always check a particular class. The dependency in that class is injected using m...

JAVA Expert Interview Questions Answers 2017

Java Basics ::  Interview Questions and Answers Home  »  Interview Questions  »  Technical Interview  »  Java Basics  » Interview Questions 1.     What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 2.     What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 3.  ...

Java Example Program to Convert List to Set

import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class ListToSet {  /**   * @author Amarjit Kumar   * @category interview questions   *   * Description: Convert List to set in java with example program   *   */  public static void main(String[] args) {   ArrayList<String> arrList= new ArrayList<>();   arrList.add("Java");   arrList.add("Java");   arrList.add("List to String");   arrList.add("Example Program");   Set<String> strSet = new HashSet<String>(arrList);   System.out.println(strSet);   System.out.println(arrList);  } } /*  * Java program to convert list to set. Convert ArrayList of string to HashSet  * in java example program How to convert List to Set in java Set<String> strSet  * = new HashSet<String>(arrList); HashSet having a constructor which will take  * list as an ar...