#Spring ApplicationContext
Explore tagged Tumblr posts
Text
What is Zero-Copy in Java?
Zero-Copy is a technique that allows data to move between storage and network devices without needing to copy it into the application layer. In traditional I/O methods, you deal with several context switches and memory copies, but Zero-Copy cuts down on that, making things faster. This approach is super helpful for high-performance applications like file servers or video streaming services.
How Zero-Copy Works Internally
To get a grip on Zero-Copy in Java, you need to understand how the Java NIO (New Input/Output) package operates. It lets data flow straight from a file channel to a socket channel through methods like transferTo() and transferFrom(). This avoids using the Java heap and saves CPU cycles, which is really useful for anyone taking a Java Full Stack Developer training Course in Coimbatore .
Benefits of Using Zero-Copy
Some of the main benefits are less CPU usage, reduced latency, and better throughput. When applications need to transfer large files, they can do it more smoothly. This is especially relevant in enterprise-level development, which is a big part of the Java Full Stack Developer Course in Coimbatore. Developers learn how to improve server-client communication using features like Zero-Copy.
Use Cases in the Real World
Zero-Copy is popular in web servers, file servers, and video streaming platforms. Companies that need fast data handling tend to use this method. Students in Java Training in Coimbatore can try out Zero-Copy in lab sessions or projects related to file transfers and socket programming.
Zero-Copy vs Traditional I/O
With traditional I/O, data gets copied several times—from disk to kernel buffer, then to user space, and finally to the socket buffer. Zero-Copy skips these extra steps. Understanding this difference is key for anyone learning about performance optimization in server-side apps.
Java NIO and Its Importance
Java NIO was introduced to support scalable and non-blocking I/O tasks. It gives you the tools to implement Zero-Copy. In a Java Course in Coimbatore, you'll learn how NIO helps create fast and efficient applications, an important skill in the Java world.
Challenges and Limitations
Even though Zero-Copy enhances performance, it’s not the best choice for every situation. It's mainly useful for large file transfers rather than small bits of data. Also, debugging can get tricky because there’s less access at the application level. Students in the Java Full Stack Developer Course learn how to wisely decide when to use Zero-Copy.
Industry Demand and Career Impact
Knowing about Zero-Copy in Java can help a developer stand out, especially in roles that require high-performance application development. Many tech companies are on the lookout for skills in this area. For those in Java Training in Coimbatore, mastering these topics can lead to great job opportunities in backend and systems development.
Tools and Libraries Supporting Zero-Copy
Besides Java NIO, other frameworks like Netty also support Zero-Copy. These tools are often covered in advanced modules of a Java Course in Coimbatore. Learners can use these libraries to build scalable, high-performance applications, especially for real-time data tasks.
Conclusion: Master Zero-Copy with the Right Training
So, Zero-Copy in Java is a handy I/O method that's key for modern Java applications. To really get the hang of it, professional training is a must. Enroll in a Java Full Stack Developer Course in Coimbatore or participate in hands-on training at Xplore IT Corp, where they teach practical skills like Zero-Copy and Java NIO.
FAQs: What is Zero-Copy in Java?
1. What is Zero-Copy in Java and why is it useful?
Zero-Copy in Java allows for direct data transfer between disk and network without moving it into application memory, which boosts performance.
2. Which Java package supports Zero-Copy operations?
Java NIO supports Zero-Copy through methods like FileChannel.transferTo() and transferFrom().
3. Can I learn Zero-Copy in a Java Course in Coimbatore?
Yes, good training centers offer detailed modules on Zero-Copy, especially in full stack and advanced Java courses.
4. Is Zero-Copy suitable for all Java applications?
No, it works best for large file transfers or fast data systems where speed is important.
5. Where can I get hands-on training in Zero-Copy and Java NIO?
You can join Xplore IT Corp, recognized for its solid Java Training in Coimbatore and Java Full Stack Developer Course.
#Spring Framework in Java#Java Dependency Injection#Java Spring Boot#Spring Bean Configuration#Java Object Lifecycle#Spring ApplicationContext#Java Backend Development#Java Programming Basics#Spring Initializer#Java Class Loader
0 notes
Text
) Explain the internal working of Spring Boot. Spring Boot works by automatically setting up default configurations based on the tools our project uses. It includes built-in servers like Tomcat to run our applications. Special starter packages make it easy to connect with other technologies. We can customize settings with simple annotations and properties files. The Spring Application class starts the app, and Spring Boot Actuator offers tools for monitoring and managing it
) How does a Spring application get started? A Spring application typically starts by initializing a Spring ApplicationContext, which manages the beans and dependencies. In Spring Boot, this is often triggered by calling SpringApplication.run() in the main method, which sets up the default configuration and starts the embedded server if necessary.
What is a Spring Bean? A Spring Bean is an object managed by the Spring framework. The framework creates, configures, and connects these beans for us, making it easier to manage dependencies and the lifecycle of objects.
Spring Boot dependency management makes it easier to handle the dependencies that our project depends on. Instead of manually keeping track of them, Spring Boot helps us manage them automatically
If a starter dependency includes conflicting versions of libraries with other dependencies, Spring Boot's dependency management resolves this by using a concept called "dependency resolution." It ensures that only one version of each library is included in the final application, prioritizing the most compatible version. This helps prevent runtime errors caused by conflicting dependencies and ensures the smooth functioning of the application
How to disable a specific auto-configuration class? We can disable specific auto-configuration classes in Spring Boot by using the exclude attribute of the @EnableAutoConfiguration annotation or by setting the spring.autoconfigure.exclude property in our application.properties or application.yml file.
Describe the flow of HTTPS requests through a Spring Boot application. In a Spring Boot application, HTTPS requests first pass through the embedded server's security layer, which manages SSL/TLS encryption. Then, the requests are routed to appropriate controllers based on URL mappings.
The @SpringBootApplication annotation is a convenience annotation that combines @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations. It is used to mark the main class of a Spring Boot application and trigger auto-configuration and component scanning. On the other hand, @EnableAutoConfiguration specifically enables Spring Boot's auto-configuration mechanism, which attempts to automatically configure our application based on the jar dependencies we have added.
I would:
Use dependency injection to manage dependencies.
Utilize Spring Profiles for environment-specific configurations.
Group related beans in separate configuration classes.
Use @ComponentScan to automatically discover beans.
You have a singleton bean that needs to be thread-safe. What approaches would you take to ensure its thread safety? I would:
Use synchronized methods or blocks to control access to critical sections.
Use ThreadLocal to provide thread-confined objects.
Implement stateless beans where possible to avoid share
To enable Spring Boot Actuator, we simply add the spring-boot-starter-actuator dependency to our project’s build file. O
The dev-tools dependency in Spring Boot provides features that enhance the development experience. It enables automatic restarts of our application when code changes are detected, which is faster than restarting manually.
To test a Spring Boot application, we use different tools and annotations. For testing the whole application together, we use @SpringBootTest. When we want to test just a part of our application, like the web layer, we use @WebMvcTest
How do you handle exceptions in Spring Boot applications? In Spring Boot, I handle errors by creating a special class with @ControllerAdvice or @RestControllerAdvice. This class has methods marked with @ExceptionHandler that deal with different types of errors. These methods help make sure that when something goes wrong, my application responds in a helpful way, like sending a clear error message or a specific error code.
) How can you disable specific auto-configuration classes in Spring Boot? We can disable specific auto-configuration classes in Spring Boot by using the @SpringBootApplication annotation with the exclude attribute. For example, @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) will disable the DataSourceAutoConfiguration class.
Versioning in REST APIs helps manage changes without breaking existing clients. It allows different versions of the API to exist at the same time, making it easier for clients to upgrade gradually. We can version REST APIs in several ways: include the version number in the URL (e.g., /api/v1/resource), add a version parameter in the URL (e.g., /api/resource?version=1), use custom headers to specify the version (e.g., Accept: application/vnd.example.v1+json), or use media types for versioning (e.g., application/vnd.example.v1+json).
ResponseEntity in Spring Boot is used to customize responses. It lets us set HTTP status codes, add custom headers, and return response data as Java objects. This flexibility helps create detailed and informative responses. For example, new ResponseEntity<>("Hello, World!", HttpStatus.OK) sends back "Hello, World!" with a status code of 200 OK.
To disable the default server and enable a different one in Spring Boot, exclude the default server dependency in the pom.xml or build.gradle file and add the dependency for the desired server. For example, to switch from Tomcat to Jetty, exclude the Tomcat dependency and include the Jetty dependency in our project configuration.
@ComponentScan annotation in Spring tells the framework where to look for components, services, and configurations. It automatically discovers and registers beans in the specified packages, eliminating the need for manual bean registration and making it easier to manage and scale the application's architecture. EnableAutoConfiguration annotation in Spring Boot tells the framework to automatically configure our application based on the libraries we have included. This means Spring Boot can set up our project with the default settings that are most likely to work well for our setup.
EnableAsync annotation in Spring enables asynchronous method execution. It allows methods to run in the background on a separate thread, improving performance by freeing up the main thread for other tasks.
RestController annotation in Spring marks a class as a RESTful web service controller. It combines @Controller and @ResponseBody, meaning the methods in the class automatically return JSON or XML responses, making it easy to create REST APIs.
EnableScheduling is an annotation in Spring Framework used to enable scheduling capabilities for methods within a Spring application. It allows methods annotated with @Scheduled to be executed based on specified time intervals or cron expressions
0 notes
Text
SpringMVC Digging Road 2 - DispatcherServler + Controller
###Role of DispatcherServlet
DispatcherServlet is the implementation of the front-end controller design pattern, which provides the centralized access point of SpringWebMVC, is responsible for the assignment of responsibilities, and can be seamlessly integrated with SpringIoC container, so as to obtain all the capabilities of Spring.
DispatcherServlet is mainly used for duty scheduling, and it is mainly used for process control. Its main duties are as follows:
```
1:File upload resolution, if the request type is multipart, file upload resolution will be performed through MultipartResolver
2:Map the request to the processor through HandlerMapping (return a HandlerExecutionChain, which includes a processor and multiple HandlerInterceptor interceptors)
3:Many types of processors (processors in HandlerExecutionChain) are supported through HandlerAdapter
4:Resolve the logical view name to the concrete view implementation through ViewResolver
5:Localization analysis
6:Render a specific view
7:If an exception is encountered during execution, it will be handed over to HandlerExceptionResolver for resolution
```
###DispatcherServler Configure
DispatcherServlet can also configure its own initialization parameters, that is, <init-param> can be configured in servlet configuration.
###The relationship of context
The general context configuration of SpringWeb project is as follows:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
```
contextConfigLocation : Represents the configuration file path used to load Bean;
contextClass : Represents the ApplicationContext implementation class used to load Bean, the default WebApplicationContext```
###Initialization order of DispatcherServlet
```
1:HttpServletBean inherits HttpServlet, so its init method will be called when the Web container starts
2:FrameworkServlet inherits HttpServletBean, initialize the Web context through initServletBean ()
3:DispatcherServlet inherits FrameworkServlet, and implemented onRefresh () method to provide some front-end controller related configurations
```
>In the DispatcherServlet of SpringMVC framework, around line 470:
/**
* This implementation calls {@link #initStrategies}.
*/
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
/**
* Initialize the strategy objects that this servlet uses.
* <p>May be overridden in subclasses in order to initialize further strategy objects.
*/
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
**The whole DispatcherServler initialization process mainly does two things:**
> * Initialize the Web context used by SpringMVC, and possibly specify the parent container (ContextLoaderListener loads the root context)
> * Initialize the policy used by DispatcherServlet, such as HandlerMapping、HandlerAdapter
###DispatcherServler Default Configure:
The default configuration of DispatcherServlet is in DispatcherServlet.properties (under the same package as DispatcherServlet class), and it is the default policy used when no configuration is specified in Spring configuration file.
It can be seen from the configuration that the DispatcherServlet will automatically register these special Bean when it starts, so we don't need to register. If we register, the default will not be registered.
###The special Bean which in DispatcherServlet
DispatcherServlet uses WebApplicationContext as the context by default, and there are some Bean in this context as follows:
####Controller
Processor/page controller, doing C in MVC, but the control logic is transferred to the front-end controller for processing requests;
####HandlerMapping
The mapping from processor is requested, and if the mapping is successful, a HandlerExecutionChain object (including a Handler processor (page processor) object and multiple HandlerInterceptor interceptors) is returned; For example, BeanNameUrlHandlerMapping maps URL and Bean name, and the Bean that is successfully mapped is the processor here;
####HandlerAdapter:
HandlerAdapter will package the processor as an adapter, thus supporting many types of processors, that is, the application of adapter design pattern, thus easily supporting many types of processors; For example, SimpleControllerHandlerAdapter will adapt the Bean that implements the Controller interface and call the handleRequest method of the processor for functional processing;
####ViewResolver
The ViewResolver will resolve the logical View name into a concrete view, for example, the InternalResourceViewResoulver will map the logical view name into a jsp view;
####LocalResolver
Localized parsing, because Spring supports internationalization, the LocaleResolver parses the Locale information of the client to facilitate internationalization;
####ThemeResolver
Theme analysis, through which multiple styles of a page can be realized, that is, the common effect similar to software skin;
####MultipartResolver
File upload analysis, used to support file upload;
####HandlerExceptionResolver
Processor exception resolution, which can map exceptions to the corresponding agreed error interface, so as to display a user-friendly interface (instead of showing users specific error information);
####RequestToViewNameTranslator
Automatically mapping the request URL to the logical view name when the processor does not return the relevant information such as the logical view name;
####FlashMapManager
It is used to manage the policy interface of FlashMap, which is used to store the output of one request, and when entering another request, it is used as the input of the request, which is usually used to redirect the scene.
###Controller brief introduction
Controller, which is the part C in MVC, is mainly responsible for the function processing part
```
1、Collect, validate and bind request parameters to command objects
2、Give the command object to the business object, and the business object will process and return the model data
3、Return ModelAndView(Model model part is the model data returned by the business object, and the view part is the logical view name)
```
###DisaptcherServler + Controller
DispatcherServlet is responsible for entrusting the request to the Controller for processing, and then selecting a specific view for rendering according to the logical view name returned by the Controller (and passing in the model data)
**The complete C (including logic control and function processing) in MVC consists of (DispatcherServlet+Controller)
###Controllerannotation
Before Spring2.5, we all defined our processor class by implementing the Controller interface or its implementation class (which is no longer recommended).
Spring2.5 introduces annotated processor support, and defines processor classes through @Controller and @RequestMapping annotations. And provides a powerful set of annotations:
> * @Controller
> * @RequestMapping
> * @RequestParam
> * @ModelAttribute
> * @SessionAttributes
> * @InitBinder
Spring3.0 introduces Restful architecture style support (supported by @PathVariable annotation and some other features), and introduces more annotation support
> * @CookieValue
> * @RequestHeader
> * @RequestBody
> * @ResponseStatus
> * @ExceptionHandler
> * @PathVariable
Spring3.1 use new HandlerMapping and HandlerAdapter to support @Controller and @RequestMapping annotation processors, Use the combination of processor mapping RequestMappingHandlerMapping and processor adapter RequestMappingHandlerAdapter to replace the processor mapping defaultannotationhandlermapping and processor adapter AnnotationMethodHandlerAdapter started in Spring2.5.
###Annotation implementation Controller
The configure of HandlerMapping and HandlerAdapter
> * Previous versions of Spring3.1:
DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter
> * The version starting with Spring3.1:
RequestMappingHandlerMapping and RequestMappingHandlerAdapter
###Example code:
Code structure reference:
https://blog.csdn.net/qq_33811662/article/details/80658813
Modify the content of spring-mvc.xml as follows:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="mvc1"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
Modify the contents of HelloController as follows:
package mvc1;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
@RequestMapping("/hello")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("进入后台控制器");
ModelAndView mv = new ModelAndView();
mv.addObject("content", "SpringMVC 初体验");
mv.setViewName("/WEB-INF/jsp/hello.jsp");
return mv;
}
}
Run the Server, enter the URL:
0 notes
Text
300+ TOP SPRING Interview Questions and Answers
SPRING Interview Questions for freshers experienced :-
1. What is Spring? Spring is an open source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO-based programming model. 2. What are benefits of Spring Framework? Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB. Inversion of control (IOC): Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects. Aspect oriented (AOP): Spring supports Aspect oriented programming and separates application business logic from system services. Container: Spring contains and manages the life cycle and configuration of application objects. MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks. Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (JTA). Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions. 3. Which are the Spring framework modules? There are around 20 modules which are generalized into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and Test. The basic modules of the Spring framework are : Spring Core Container This layer is basically the core of Spring Framework. It contains the following modules: Core module Bean module Context module Expression Language module Data Access/Integration This layer provides support to interact with the database. It contains the following modules: JDBC module Object-Relational Mapping (ORM) module Java Messaging Service (JMS) module Object XML Mappers (OXM) module Transaction Management module Web This layer provides support to create web application. It contains the following modules: Web module Web-MVC module Web-Socket module Web-Portlet module Aspect Oriented Programming (AOP) In this layer you can use Advices, Pointcuts etc., to decouple the code. Instrumentation – This layer provides support to class instrumentation and classloader implementations. Test This layer provides support to testing with JUnit and TestNG. Messaging This module provides support for STOMP. It also supports an annotation programming model that is used for routing and processing STOMP messages from WebSocket clients. Aspects This module provides support to integration with AspectJ. 4. Explain the Core Container (Application context) module This is the basic Spring module, which provides the fundamental functionality of the Spring framework. BeanFactory is the heart of any spring-based application. Spring framework was built on the top of this module, which makes the Spring container. 5. BeanFactory implementation example A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code. The most commonly used BeanFactory implementation is the XmlBeanFactory class. 6. XMLBeanFactory The most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application. 7. Explain the AOP module The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring. 8. Explain the JDBC abstraction and DAO module With the JDBC abstraction and DAO module we can be sure that we keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. It provides a layer of meaningful exceptions on top of the error messages given by several database servers. It also makes use of Spring’s AOP module to provide transaction management services for objects in a Spring application. 9. Explain the object/relational mapping integration module Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provides support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC. 10. Explain the web module The Spring web module is built on the application context module, providing a context that is appropriate for web-based applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.
SPRING Interview Questions 11. Explain the Spring MVC module MVC framework is provided by Spring for building web applications. Spring can easily be integrated with other MVC frameworks, but Spring’s MVC framework is a better choice, since it uses IoC to provide for a clean separation of controller logic from business objects. With Spring MVC you can declaratively bind request parameters to your business objects. 12. Spring configuration file Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other. 13. How can we have multiple Spring configuration files? web.xml contextConfigLocation: you can load them all into your Web application context via the ContextConfigLocation element. You’re already going to have your primary applicationContext here, assuming you’re writing a web application. All you need to do is put some white space between the declaration of the next context. applicationContext.xml import resource: you can add your primary applicationContext.xml to the web.xml and then use import statements in that primary context. 14. What are the common implementations of the ApplicationContext? The FileSystemXmlApplicationContext container loads the definitions of the beans from an XML file. The full path of the XML bean configuration file must be provided to the constructor. The ClassPathXmlApplicationContext container also loads the definitions of the beans from an XML file. Here, you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH. The WebXmlApplicationContext: container loads the XML file with definitions of all beans from within a web application. 15. What is the difference between Bean Factory and ApplicationContext? Application contexts provide a means for resolving text messages, a generic way to load file resources (such as images), they can publish events to beans that are registered as listeners. In addition, operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable. 16. What are some of the best practices for Spring Framework? Some of the best practices for Spring Framework are: Define singleton beans with names same as their class or interface names Place Spring bean configuration files under a folder instead of root folder Give common prefixes or suffixes to Spring bean configuration files Avoid using import elements within Spring XML configuration files as much as possible Stay away from auto wiring in XML based bean configurations Always externalize bean property values with property placeholders Select default version-less XSD when importing namespace definitions Always place classpath prefix in resource paths Create a setter method even though you use field level auto wiring Create a separate service layer even though service methods barely delegate their responsibilities to corresponding DAO methods 17. What are the various ways of using Spring Framework? You can use Spring Framework: for writing web applications for exposing RESTful services to secure your web applications for communicating with databases for handling long running jobs to handle external resources or systems you have to work with for testing purposes for standalone java projects to convert your application into an executable to integrate Social Media into your applications 18. How can we use Spring to create Restful Web Service returning JSON response? Any Spring @RestController in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath. 19. Spring vs Spring MVC vs Spring Boot? Spring: the most important feature of Spring is Dependency Injection or Inversion of Control. Spring MVC: is a complete HTTP oriented MVC framework managed by the Spring Framework and based in Servlets. It would be equivalent to JSF in the JavaEE stack. Spring Boot: is a utility for setting up applications quickly, offering an out of the box configuration in order to build Spring powered applications. 20. What does a Spring application look like? Interface: An interface that defines the functions. Bean class: It contains properties, its setter and getter methods, functions etc. Spring AOP: Provides the functionality of cross-cutting concerns. The configuration XML file: Contains the information of classes and how to configure them. The Client program: uses the function. Dependency Injection 21. What is Spring IoC container? The Spring IoC is responsible for creating the objects,managing them with dependency injection (DI), wiring them together, configuring them, as also managing their complete lifecycle. 22. What are the benefits of IOC? IOC or dependency injection minimizes the amount of code in an application. It makes easy to test applications, since no singletons or JNDI lookup mechanisms are required in unit tests. Loose coupling is promoted with minimal effort and least intrusive mechanism. IOC containers support eager instantiation and lazy loading of services. 23. How many types of IOC containers are there in spring? BeanFactory: A BeanFactory is essentially nothing more than the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. The BeanFactory enables you to read bean definitions and access them using the bean factory. ApplicationContext: The ApplicationContext is the central interface within a Spring application for providing configuration information to the application. It is read-only at run time, but can be reloaded if necessary and supported by the application. A number of classes implement the ApplicationContext interface, allowing for a variety of configuration options and types of applications. 24. BeanFactory vs ApplicationContext Application Context: Bean instantiation/wiring Automatic BeanPostProcessor registration Automatic BeanFactoryPostProcessor registration Convenient MessageSource access (for i18n) ApplicationEvent publication BeanFactor: Bean instantiation/wiring 25. What is Dependency Injection in Spring? Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept, and it can be expressed in many different ways.This concept says 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 (the IOC container) is then responsible for hooking it all up. 26. What is the difference between Tight Coupling and Loose Coupling? Tight Coupling: Tight coupling is when a group of classes are highly dependent on one another. Loose Coupling: Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns. 27. What are the different types of IoC (dependency injection)? Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class. Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. 28. Which DI would you suggest Constructor-based or setter-based DI? You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for mandatory dependencies and setters for optional dependencies. 29. What are Spring beans? The Spring Beans are Java Objects that form the backbone of a Spring application. They are instantiated, assembled, and managed by the Spring IoC container. These beans are created with the configuration metadata that is supplied to the container, for example, in the form of XML definitions. Beans defined in spring framework are singleton beans. There is an attribute in bean tag named "singleton" if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans. 30. What does a Spring Bean definition contain? A Spring Bean definition contains all configuration metadata which is needed for the container to know how to create a bean, its lifecycle details and its dependencies. 31. How do you provide configuration metadata to the Spring Container? There are three important methods to provide configuration metadata to the Spring Container: XML based configuration file. Annotation-based configuration Java-based configuration 32. How do you define the scope of a bean? When defining a in Spring, we can also declare a scope for the bean. It can be defined through the scope attribute in the bean definition. For example, when Spring has to produce a new bean instance each time one is needed, the bean’s scope attribute to be prototype. On the other hand, when the same instance of a bean must be returned by Spring every time it is needed, the the bean scope attribute must be set to singleton. 33. Explain the bean scopes supported by Spring There are five scoped provided by the Spring Framework supports following five scopes: In singleton scope, Spring scopes the bean definition to a single instance per Spring IoC container. In prototype scope, a single bean definition has any number of object instances. In request scope, a bean is defined to an HTTP request. This scope is valid only in a web-aware Spring ApplicationContext. In session scope, a bean definition is scoped to an HTTP session. This scope is also valid only in a web-aware Spring ApplicationContext. In global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring ApplicationContext. The default scope of a Spring Bean is Singleton. 34. Are Singleton beans thread safe in Spring Framework? No, singleton beans are not thread-safe in Spring framework. 35. Explain Bean lifecycle in Spring framework The spring container finds the bean’s definition from the XML file and instantiates the bean. Spring populates all of the properties as specified in the bean definition (DI). If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method. If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method. If the bean implements IntializingBean, its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called. If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called. If the bean implements DisposableBean, it will call the destroy() method. 36. Which are the important beans lifecycle methods? Can you override them? There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container. The bean tag has two important attributes (init-method and destroy-method) with which you can define your own custom initialization and destroy methods. There are also the correspondive annotations(@PostConstruct and @PreDestroy). 37. What are inner beans in Spring? When a bean is only used as a property of another bean it can be declared as an inner bean. Spring’s XML-based configuration metadata provides the use of element inside the or elements of a bean definition, in order to define the so-called inner bean. Inner beans are always anonymous and they are always scoped as prototypes. 38. How can you inject a Java Collection in Spring? Spring offers the following types of collection configuration elements: The type is used for injecting a list of values, in the case that duplicates are allowed. The type is used for wiring a set of values but without any duplicates. The type is used to inject a collection of name-value pairs where name and value can be of any type. The type can be used to inject a collection of name-value pairs where the name and value are both Strings. 39. What is bean wiring? Wiring, or else bean wiring is the case when beans are combined together within the Spring container. When wiring beans, the Spring container needs to know what beans are needed and how the container should use dependency injection to tie them together. 40. What is bean autowiring? The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactory without using and elements. 41. Explain different modes of autowiring? The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection: no: This is default setting. Explicit bean reference should be used for wiring. byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. byType: When autowiring by datatype, the 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 exist, a fatal exception is thrown. constructor: This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType. 42. Are there limitations with autowiring? Limitations of autowiring are: Overriding: You can still specify dependencies using and settings which will always override autowiring. Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes. Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring. 43. Can you inject null and empty string values in Spring? Yes, you can. Spring Annotations 44. What are some of the important Spring annotations? Some of the Spring annotations that I have used in my project are: 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. Required – This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated. 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 – provides more fine-grained control over where and how autowiring should be accomplished. It can be used to autowire bean on the setter method just like @Required annotation, on the constructor, on a property or pn methods with arbitrary names and/or multiple arguments. Qualifier – When there are more than one beans of the same type and only one is needed to be wired with a property, the @Qualifier annotation is used along with @Autowired annotation to remove the confusion by specifying which exact bean will be wired. Scope – for configuring scope of the spring bean. Configuration – indicates that the class can be used by the Spring IoC container as a source of bean definitions. ComponentScan – all the classes available under a package will be scanned when this annotation is applied. Bean – for java based configurations, tells spring that a method annotated with @Bean will return an object that should be registered as a bean in the spring application context. AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcut etc. 45. What does the @RequestParam annotation do? The @RequestParam annotation in spring binds the parameter values of a query string to the method argument of a controller. 46. What is the importance of the annotation @Primary When there are multiple beans of the same data-type, developers use the Spring-specific @Primary annotation that automatically gives the higher preference to a particular bean. This annotation can be used on any class directly or indirectly annotated with the @Component annotation or on methods annotated with the @Bean annotation. 47. What is the difference between the Configuration types XML and Annotation? Advantages of the annotation: All the information is in a single file When the class changes, no need to modify the xml file Advantages of XML file: Clear separation between the POJO and its behavior When you do not know which POJO is responsible for the behavior, it is easier to find that POJO 48. What is the role of @SpringBootApplication? The @SpringBootApplication annotation was introduced in Spring Boot 1.2.0 and it enables the auto-configuration feature. This annotation encapsulates the working of three different annotations: @Configuration: Allows the developers to explicitly register the beans @ComponentScan: Enables the component-scanning so that the controller class and other components will be automatically discovered and registered as beans in spring’s application context @EnableAutoConfiguration: Enables the auto-configuration feature of spring boot This annotation takes up the following optional parameters: exclude: Excludes the list of classes from the auto-configuration excludeNames: Excludes the list of fully qualified class names from the auto configuration scanBasePackage: Provides the list of packages which must be applied for scanning scanBasePackageClasses: Provides the list of classes in the other package which must be applied for scanning 49. Explain the @InitBinder? This annotation is decorated on a method in which a date format is declared, and throughout the class, the defined date format is used. Whenever the binding happens with a date field @InitBinder; annotation says to use the CustomDateEditor, which in return uses the date format mentioned in @InitBinder. 50. Define @ControllerAdvice? Classes with @ControllerAdvice can be declared explicitly as Spring beans or auto-detected via classpath scanning. All such beans are sorted via AnnotationAwareOrderComparator, i.e. based on @Order and Ordered, and applied in that order at runtime. For handling exceptions, an @ExceptionHandler will be picked on the first advice with a matching exception handler method. For model attributes and InitBinder initialization, @ModelAttribute and @InitBinder methods will also follow @ControllerAdvice order. 51. Can we send an Object as the response of Controller handler method? Yes we can send JSON or XML based response in restful web services, using the @ResponseBody annotation. 52. Explain @ModelAttribute? The @ModelAttribute annotation refers to the property of the Model object and is used to prepare the model data. This annotation binds a method variable or the model object to a named model attribute. The annotation accepts an optional value which indicates the name of the model attribute. The @ModelAttribute annotation can be used at the parameter level or the method level. The use of this annotation at the parameter level is to accept the request form values while at the method level is to assign the default values to a model. Let me explain you further with the help of some examples. 53. @RequestMapping annotation The @RequestMapping annotation is used to map the web request onto a handler class (i.e. Controller) or a handler method and it can be used at the Method Level or the Class Level. If developers use the @RequestMapping annotation at a class level, it will be as a relative path for the method level path. 54. What is Spring Java-Based Configuration? Give some annotation example. Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations. An example is the @Configuration annotation, that indicates that the class can be used by the Spring IoC container as a source of bean definitions. Another example is the@Bean annotated method that will return an object that should be registered as a bean in the Spring application context. 55. What is Annotation-based container configuration? An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration. 56. How do you turn on annotation wiring? Annotation wiring is not turned on in the Spring container by default. In order to use annotation based wiring we must enable it in our Spring configuration file by configuring element. Spring Data Access 57. Which classes are present in spring JDBC API? Spring framework provides the following approaches for Jdbc database access: JdbcTemplate SimpleJdbcTemplate NamedParameterJdbcTemplate SimpleJdbcInsert SimpleJdbcCall 58. How can JDBC be used more efficiently in the Spring framework? When using the Spring JDBC framework the burden of resource management and error handling is reduced. So developers only need to write the statements and queries to get the data to and from the database. JDBC can be used more efficiently with the help of a template class provided by Spring framework, which is the JdbcTemplate (example here). 59. JdbcTemplate JdbcTemplate class provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling. 60. How can you fetch records by spring JdbcTemplate? There are two interfaces that can be used to fetch records from the database: ResultSetExtractor RowMapper 61. What is the advantage of NamedParameterJdbcTemplate? NamedParameterJdbcTemplate is built upon JDBCTemplate which is provided by spring and used for lower level communication with databases. It makes possible to pass SQL query arguments as key value pairs. As a result the program code is much more readable and therefore serves as better documentation compared to the indexed or the “?” placeholder approach. The latter is harder to follow specially if the number of parameters is huge. 62. What is Spring JDBCTemplate class and how to use it? The JdbcTemplate class executes SQL queries, update statements and stored procedure calls, performs iteration over ResultSets and extraction of returned parameter values. It handles the creation and release of resources, thus avoiding errors such as forgetting to close the connection. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package. 63. What is the difference between JDBC and Spring JDBC? Spring JDBC value-add provided by the Spring Framework’s on top JDBC layer Define connection parameters Open the connection Specify the statement Prepare and execute the statement Set up the loop to iterate through the results (if any) Do the work for each iteration Process any exception Handle transactions Close the connection 64. Spring DAO support The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows us to switch between the persistence technologies fairly easily and to code without worrying about catching exceptions that are specific to each technology. 65. What are the ways to access Hibernate by using Spring? There are two ways to access Hibernate with Spring: Inversion of Control with a Hibernate Template and Callback. Extending HibernateDAOSupport and Applying an AOP Interceptor node. 66. ORM’s Spring support Spring supports the following ORM’s: Hibernate iBatis JPA (Java Persistence API) TopLink JDO (Java Data Objects) OJB 67. How can we integrate Spring and Hibernate using HibernateDaoSupport? Use Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps: Configure the Hibernate SessionFactory Extend a DAO Implementation from HibernateDaoSupport Wire in Transaction Support with AOP 68. Types of the transaction management Spring support Spring supports two types of transaction management: Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain. Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions. 69. What are the benefits of the Spring Framework’s transaction management? It provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO. It provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA. It supports declarative transaction management. It integrates very well with Spring’s various data access abstractions. 70. Which Transaction management type is more preferable? Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container. Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code. Spring Aspect Oriented Programming (AOP) 71. Explain AOP Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. 72. What are the advantages of spring AOP? a. It is non-invasive Your service/domain classes get advised by the aspects (cross cutting concerns) without adding any Spring AOP related classes or interfaces into the service/domain classes. Allows the developer to concentrate on the business code, instead the cross cutting concerns. b. Its implemented in pure Java No need for a special compilation unit, or a special class loader c. It uses Spring’s IOC for dependency injection Aspects can be configured as normal spring beans. d. As any other AOP framework, it weaves cross cutting concerns into the classes, without making a call to the cross cutting concerns from those classes. e. Centralize or modularize the cross cutting concerns Easy to maintain and make changes to the aspects Changes need to be made in one place. In one of your classes you don’t want to have logging, it can easily be achieved by modifying the point cut in the respective aspect (logging aspect). So you need to make changes in only one place. f. Provision to create aspects using schema based (XML configuration) or @AspectJ annotation based style. g. Easy to configure 73. What are the AOP implementation? AOP implementations: Spring AOP: Runtime weaving through proxy is done It supports only method level PointCut It is DTD based Apache AspectJ Compile time weaving through AspectJ Java tools is done It suports field level Pointcuts It is schema based and Annotation configuration JBoss AOP JBoss AOP is not only a framework, but also a prepackaged set of aspects that are applied via annotations, pointcut expressions, or dynamically at runtime. Some of these include caching, asynchronous communication, transactions, security, remoting, and many many more. 74. What are the AOP terminology? Aspect Advice Pointcut JoinPoint Introduction Target Object AOP Proxy Weaving 75. Aspect The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. It ia a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes annotated with the @Aspect annotation (@AspectJ style). 76. Join point The join point represents a point in an application where we can plug-in an AOP aspect. It is the actual place in the application where an action will be taken using Spring AOP framework. 77. Advice The advice is the actual action that will be taken either before or after the method execution. This is actual piece of code that is invoked during the program execution by the Spring AOP framework. Spring aspects can work with five kinds of advice: before: Run advice before the a method execution. after: Run advice after the a method execution regardless of its outcome. after-returning: Run advice after the a method execution only if method completes successfully. after-throwing: Run advice after the a method execution only if method exits by throwing an exception. around: Run advice before and after the advised method is invoked. 78. Pointcut The pointcut is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns. 79. What is Introduction? An Introduction allows us to add new methods or attributes to existing classes. 80. What is Target object? The target object is an object being advised by one or more aspects. It will always be a proxy object. It is also referred to as the advised object. 81. What is a Proxy? A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same. 82. What are the different types of AutoProxying? BeanNameAutoProxyCreator DefaultAdvisorAutoProxyCreator Metadata autoproxying 83. What is Weaving? What are the different points where weaving can be applied? Weaving is the process of linking aspects with other application types or objects to create an advised object. Weaving can be done at compile time, at load time, or at runtime. 84. What is the difference between concern and cross-cutting concern in Spring AOP The Concern is behavior we want to have in a module of an application. A Concern may be defined as a functionality we want to implement. The cross-cutting concern is a concern which is applicable throughout the application and it affects the entire application. For example, logging, security and data transfer are the concerns which are needed in almost every module of an application, hence they are cross-cutting concerns. 85. Explain XML Schema-based aspect implementation? In this implementation case, aspects are implemented using regular classes along with XML based configuration. 86. Explain annotation-based (@AspectJ based) aspect implementation This implementation case (@AspectJ based implementation) refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations. Spring Model View Controller (MVC) 87. What is Spring MVC framework? Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide a clean separation of controller logic from business objects. It also allows to declaratively bind request parameters to business objects. 88. What are the minimum configurations needed to create Spring MVC application? For creating a simple Spring MVC application, we would need to do the 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. 89. List out all the concepts that are available in the MVC Architecture? The browser sends a request to DispatcherServlet DispatcherServlet knows the HanderMapping and can find the appropriate controllers Controllers execute the request and put the data in the model and return back the view name to the DispatcherServlet. DispatcherServlet uses the view name and ViewResolver to map to the view. 90. DispatcherServlet The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. 91. WebApplicationContext The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with. 92. What is Controller in Spring MVC framework? Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers. 93. How would you relate Spring MVC Framework to MVC architecture? Spring MVC framework: The Spring Framework is an open source application framework and inversion of control container for the Java platform. MVC architecture: Model View Controller (MVC) as it is popularly called, is a software design pattern for developing web applications 94. What is ViewResolver in Spring MVC? Spring provides ViewResolver, which enable you to render models in a browser without tying you to a specific view technology. Out of the box, Spring enables you to use JSPs, Velocity templates and XSLT views, for example. The two interfaces which are important to the way Spring handles views are ViewResolver and View. The ViewResolver provides a mapping between view names and actual views. The View interface addresses the preparation of the request and hands the request over to one of the view technologies. 95. What is a MultipartResolver and when its used? Spring MVC provide multipart support with MultipartResolver. The MultipartResolver parses inbound multipart requests. You can enable multipart support by registering a MultipartResolver bean in the DispatcherServlet application context. 96. How to upload file in Spring MVC Application? Spring provides built-in support for uploading files through MultipartResolver interface implementations. There is also a validator for the field, which will be used to check if the file uploaded is of size greater than zero. There is finally a simple view that contains a form with the option to upload a file. 97. How to validate form data in Spring Web MVC Framework? There are 3 different ways to perform validation : using annotation, manually, or a mix of both. 98. What is Spring MVC Interceptor and how to use it? Spring’s handler mapping mechanism includes handler interceptors, which are useful when you want to apply specific functionality to certain requests, for example, checking for a principal. Interceptors must implement HandlerInterceptor from the org.springframework.web.servlet package. This interface defines three methods: preHandle is called before the actual handler is executed. postHandle is called after the handler is executed. afterCompletion is called after the complete request has finished. Authentication and authorization 99. What is Spring Security? Spring security is one of the most important modules of the Spring framework. It enables the developers to integrate the security features easily and in a managed way. In the following example, we will show how to implement Spring Security in a Spring MVC application. 100. Why Spring Boot? Here are some useful benefits of using Spring Boot: Automatic configuration of an application uses intelligent defaults based on the classpath and the application context, but they can be overridden to suit the developer’s requirements as needed. When creating a Spring Boot Starter project, you select the features that your application needs and Spring Boot will manage the dependencies for you. A Spring Boot application can be packaged as a JAR file. The application can be run as a standalone Java application from the command line using the java -jar command. When developing a web application, Spring Boot configures an embedded Tomcat server so that it can be run as a standalone application. (Tomcat is the default, but you can configure Jetty or Undertow instead.) You can package the application as a WAR file and deploy it to an external servlet container if you prefer Spring Boot includes many useful non-functional features (such as security and health checks) right out of the box. SPRING Questions and Answers Pdf Download Read the full article
0 notes
Text
Spring IoC Containers – Types of Spring Container
Spring IoC Containers – Types of Spring Container
Spring IoC Containers
The Spring container is the core of Spring Framework. The container, use for creating the objects and configuring them. Also, Spring IoC Containers use for managing the complete lifecycle from creation to its destruction. It uses Dependency Injection (DI) to manage components and these objects are called Spring Beans. The container uses configuration metadata which represent by Java code, annotations or XML along with Java POJO classes as seen below.
Do you know Features of Spring Framework?
Spring IoC Containers – Types of Spring ContainerTypes of IoC Containers in Spring
This are the two types of Spring IoC Containers, let’s see one by one:
a. Spring BeanFactory Container
Spring BeanFactory Container is the simplest container which provides basic support for DI. It is defined by org.springframework.beans.factory.BeanFactory interface. There are many implementations of BeanFactory interface that come with Spring where XmlBeanFactory being the most commonly used class. XmlBeanFactory reads configuration metadata from XML file for creating a fully configured application. The BeanFactory container prefer, where resources are limited to mobile devices or applet-based applications. Let’s learn Spring Framework Architecture with Modules You will look at a working example with Eclipse IDE with the following steps for creating Spring application
Create a project with a name SpringExample and a package packagecom.example. These should be under src folder of the created project.
Add the needed Spring libraries using Add External JARs.
Create Java classes HelloWorld and MainApp under the package packagecom .example.
Create Beans config file Beans.xml under src folder.
At last, create content of all Java files and Beans configuration file and run the file as below.
The code of HelloWorld.java is as shown.
package com.example;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
The following is the code of MainApp.java.
package com.example;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class MainApp {
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml"));
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
obj.getMessage();
}
}<span style="background-color: #fafafa;color: #333333;font-family: Verdana, Geneva, sans-serif;font-size: 16px;font-weight: inherit"> </span>
There are some points which should be taken about the main program:
Write a factory object where you have used APIXmlBeanFactory() to load bean config file in CLASSPATH.
Use getBean() which uses bean ID to return a generic object to get the required bean.
Let’s See What is Spring Boot CLI with Example Following is the XML code for Beans.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"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "helloWorld" class = "com.example.HelloWorld">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
After you run the application you will see the following message as output. Your Message: Hello World!
b. Spring ApplicationContext Container
The ApplicationContext container is Spring’s advanced container. It is defined by org.springframework.context.ApplicationContext interface. The ApplicationContext container has all the functionalities of BeanFactory. It is generally recommended over BeanFactory. The most common implementations of ApplicationContext are:
FileSystemXmlApplicationContext: It is a type of container which loads the definitions of beans from an XML file. For that, you should be able to provide the full path of the XML bean config file to a constructor.
ClassPathXmlApplicationContext: This type of container loads definitions of the beans from XML file but you don’t need to provide the full path of the XML file. Only the CLASSPATH has to set properly as this container will look like Bean config XML file.
WebXmlApplicationContext: This type of container loads the XML file with all bean definitions within a web application.
i. Working of Eclipse IDE
You will better understand with a working example in Eclipse IDE with the following steps:
Create a project with a name SpringExample and a package packagecom.example. These should under src folder of the created project.
Add the needed Spring libraries using Add External JARs.
Create Java classes HelloWorld and MainApp under the package packagecom .example.
Create Beans config file Beans.xml under src folder.
At last, create content of all Java files and Beans configuration file and run the file as below.
Follow this link this know more about Spring JDBC Framework – JDBC Template with Eclipse IDE The code for HelloWorld.java file:
package com.example;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
The code for MainApp.java:
package com.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext
("C:/Users/ADMIN/workspace/HelloSpring/src/Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
ii. Some Points
Some points should note about the main program:
Using framework API FileSystemXmlApplicationContext create a factory object. This API takes care of creating and initializing all objects.
Use getBean() which uses bean ID to return a generic object to get the required bean.
The code for Beans.xml is as given:
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "helloWorld" class = "com.example.HelloWorld">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
After creating source and bean config files, run the application. You will see the following as your output. Your Message: Hello World! So, this was all about Spring IoC Containers. Hope you like our explanation.
Conclusion
Hence, in this Spring Containers tutorial, we learned two types of Spring IoC Containers: BeanFactory Container and ApplicationContext Container in Spring Framework. Furthermore, if you have any query regarding IoC Containers, feel free to ask in the comment section.
0 notes
Text
Integration Testing in Spring Boot
Overview When we talk about integration testing for a spring boot application, it is all about running an application in ApplicationContext and run tests. Spring Framework does have a dedicated test module for integration testing. It is known as spring-test. If we are using spring-boot, then we need to use spring-boot-starter-test which will internally use spring-test and other dependent libraries. In this article, we are going to see how integration tests can be run for a Spring Boot application. https://goo.gl/5dehiK
0 notes
Text
Spring Basic (English)
1.Why should you use Spring?
Lightweight: Spring is lightweight when it comes to size and transparency.
Inversion of control (IOC): Objects give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Container: Spring contains and manages the life cycle and configuration of application objects.
MVC Framework: Provides a great alternative to other web frameworks such as Struts.
Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local and scale up to global.
Exception Handling: Spring translate technology-specific exceptions into consistent, unchecked exceptions.
2. Modules
Core,
Bean,
Context,
Expression Language,
JDBC,
ORM,
OXM,
JMS,
Transaction,
Web,
Web-Servlet,
Web-Struts,
Web-Portlet
3. Inversion of Control (IOC)
This concept says that you do not create your objects but describe how they should be created. Dependency Injection is an example of it (spring injects dependencies into your attributes with @Autowire).
Containers - Bean Factory : Container providing basic support. - Spring ApplicationContext: adds more enterprise-specific functionality.
Types - Constructor-based: The container invokes a class constructor with a number of arguments. - Setter-based: Calling setter methods on your beans after invoking a no-argument constructor.
4. Scopes
Types instances that should be returned from Spring container:
Singleton: Bean definition to a single instance, it's the default.
Prototype: Single bean definition to have any number of object instances.
Request: A bean definition to an HTTP request
Session: A bean definition to an HTTP session
Global-session: A bean definition to a global HTTP session
5. Aspect-oriented programming (AOP)
It is a programming technique that allows programmers to modularize crosscutting concerns, or behavior.
Concern: It may be defined as a functionality we want to implement.
Cross-cutting concern: It's a concern which is applicable throughout the application and it affects the entire application.
Advice: This is the actual action to be taken either before or after the method execution. - Before: Run advice before a method execution. - After: Run advice after a method execution regardless of its outcome. - After-returning: Run advice after a method execution only if method completes successfully. - After-throwing: Run advice after a method execution only if method exits by throwing an exception. - Around: Run advice before and after the advised method is invoked.
Join: This represents a point in your application where you can plug-in AOP aspect.
Pointcut : This is a set of one or more join points where an advice should be executed.
6. Annotations
@Required: Indicates that the affected bean property must be populated at configuration time.
@Autowired: It can be used to autowire bean on the setter method, constructor, a property or methods with arbitrary names and/or multiple arguments.
@Qualifier: You can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired, in case of more than one bean.
@Configuration: Indicates that the class can be used by the Spring IoC container as a source of bean definitions.
@Bean: It tells Spring that a method will return an object that should be registered as a bean.
@WebApplicationContext (@ApplicationContext): It defines a class as the main class in the project.
@Controller: Indicates that a class serves the role of a controller.
@RequestMapping: It is used to map a URL to either an entire class or a particular handler method.
@PostConstruct: This annotation can be used as an alternate of initialization callback.
@PreDestroy: This annotation can be used as an alternate of destruction callback.
@Resource: It takes a 'name' attribute which will be interpreted as the bean name to be injected.
@ResponseBody: Indicates that the return type should be written straight to the HTTP response.
@RequestBody: Indicate that a method parameter should be bound to the body of the HTTP request.
1 note
·
View note
Text
Spring Interview Questions and Answers
Spring Interview Questions
What is Spring Framework?
What are some of the important features and advantages of Spring Framework?
What do you understand by Dependency Injection?
How do we implement DI in Spring Framework?
What are the new features in Spring 5?
What is Spring WebFlux?
What are the benefits of using Spring Tool Suite?
Name some of the important Spring Modules?
What do you understand by Aspect Oriented Programming?
What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?
What is the difference between Spring AOP and AspectJ AOP?
What is Spring IoC Container?
What is a Spring Bean?
What is the importance of Spring bean configuration file?
What are different ways to configure a class as Spring Bean?
What are different scopes of Spring Bean?
What is Spring Bean life cycle?
How to get ServletContext and ServletConfig object in a Spring Bean?
What is Bean wiring and @Autowired annotation?
What are different types of Spring Bean autowiring?
Does Spring Bean provide thread safety?
What is a Controller in Spring MVC?
What’s the difference between @Component, @Repository & @Service annotations in Spring?
What is DispatcherServlet and ContextLoaderListener?
What is ViewResolver in Spring?
What is a MultipartResolver and when it’s used?
How to handle exceptions in Spring MVC Framework?
How to create ApplicationContext in a Java Program?
Can we have multiple Spring configuration files?
What is ContextLoaderListener?
What are the minimum configurations needed to create Spring MVC application?
How would you relate Spring MVC Framework to MVC architecture?
How to achieve localization in Spring MVC applications?
How can we use Spring to create Restful Web Service returning JSON response?
What are some of the important Spring annotations you have used?
Can we send an Object as the response of Controller handler method?
How to upload file in Spring MVC Application?
How to validate form data in Spring Web MVC Framework?
What is Spring MVC Interceptor and how to use it?
What is Spring JdbcTemplate class and how to use it?
How to use Tomcat JNDI DataSource in Spring Web Application?
How would you achieve Transaction Management in Spring?
What is Spring DAO?
How to integrate Spring and Hibernate Frameworks?
What is Spring Security?
How to inject a java.util.Properties into a Spring Bean?
Name some of the design patterns used in Spring Framework?
What are some of the best practices for Spring Framework?
Spring Interview Questions and Answers
Spring is one of the most widely used Java EE framework. 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.
I like spring because it provides a lot of features and different modules for specific tasks such as Spring MVC and Spring JDBC. Since it’s an open source framework with a lot of online resources and active community members, working with the Spring framework is easy and fun at the same time.
Recommended Read: 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.
Some of the advantages of using Spring Framework are:
Reducing direct dependencies between different components of the application, usually Spring IoC container is responsible for initializing resources or beans and inject them as dependencies.
Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purposes.
Reduces the amount of boiler-plate code, such as initializing objects, open/close resources. I like JdbcTemplate class a lot because it helps us in removing all the boiler-plate code that comes with JDBC programming.
Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we don’t need Spring transaction management features, we don’t need to add that dependency on our project.
Spring framework support most of the Java EE features and even much more. It’s always on top of the new technologies, for example, there is a Spring project for Android to help us write better code for native Android applications. This makes spring framework a complete package and we don’t need to look after the different framework for different requirements.
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.
Read more at Dependency Injection Tutorial. We can also use Google Guice for Dependency Injection to automate the process of dependency injection. But in most of the cases, we are looking for more than just dependency injection and that’s why Spring is the top choice for this.
We can use Spring XML based as well as Annotation-based configuration to implement DI in spring applications. For better understanding, please read Spring Dependency Injection example where you can learn both the ways with JUnit test case. The post also contains a sample project zip file, that you can download and play around to learn more.
Spring 5 brought a massive update to Spring framework. Some of the new features in Spring 5 are:
Spring 5 runs on Java 8+ and supports Java EE 7. So we can use lambda expressions and Servlet 4.0 features. It’s good to see Spring trying to support the latest versions.
Spring Framework 5.0 comes with its own Commons Logging bridge; spring-jcl instead of standard Commons Logging.
Support for providing spring components information through index file “META-INF/spring.components” rather than classpath scanning.
Spring WebFlux brings reactive programming to the Spring Framework.
Spring 5 also supports Kotlin programming now. This is a huge step towards supporting functional programming, just as Java is also moving towards functional programming.
Support for JUnit 5 and parallel testing execution in the Spring TestContext Framework.
You can read about these features in more detail at Spring 5 Features.
Spring WebFlux is the new module introduced in Spring 5. Spring WebFlux is the first step towards the reactive programming model in spring framework.
Spring WebFlux is the alternative to the Spring MVC module. Spring WebFlux is used to create a fully asynchronous and non-blocking application built on the event-loop execution model.
You can read more about it at Spring WebFlux Tutorial.
We can install plugins into Eclipse to get all the features of Spring Tool Suite. However, STS comes with Eclipse with some other important kinds of stuff such as Maven support, Templates for creating different types of Spring projects and tc server for better performance with Spring applications.
I like STS because it highlights the Spring components and if you are using AOP pointcuts and advice, then it clearly shows which methods will come under the specific pointcut. So rather than installing everything on our own, I prefer using STS when developing Spring-based applications.
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.
Enterprise applications have some common cross-cutting concerns that are applicable to 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 are 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. Read more about Spring AOP support at Spring AOP Example.
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. You can think of Advices as Spring interceptors or Servlet Filters.
Pointcut: Pointcut are regular expressions that are 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 a specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join point 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 the argument type is determined.
These concepts seems confusing at first, but if you go through Spring Aspect, Advice Example then you can easily relate to them.
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 shortcomings of Spring AOP is that it can be applied only to the beans created through Spring Context.
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 makes 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.
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.
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 initializes 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.
There are three different ways to configure Spring Bean.
XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean. For example:
Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:
Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes. For example:
<bean name="myBean" class="com.journaldev.spring.beans.MyBean"></bean>
@Configuration @ComponentScan(value="com.journaldev.spring.main") public class MyConfiguration { @Bean public MyService getService(){ return new MyService(); } }
To get this bean from spring context, we need to use following code snippet:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( MyConfiguration.class); MyService service = ctx.getBean(MyService.class);
<context:component-scan base-package="com.journaldev.spring" />
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.
Spring Beans are initialized by Spring Container and all the dependencies are also injected. When the 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. For more details, please read Spring Bean Life Cycle Methods.
There are two ways to get Container specific objects in the spring bean.
Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete example of these aware interfaces, please read Spring Aware Interfaces
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;
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 the spring framework also supports auto-wiring. 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.
For more details about @Autowired annotation, please read Spring Autowire Example.
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. For more details about these options, please read Spring Bean Autowiring.
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.
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 a 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 @RequestMapping annotation to define handler methods for specific URI mapping.
@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.
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.
ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file. For example:
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean>
InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.
MultipartResolver interface is used for uploading files – CommonsMultipartResolver and StandardServletMultipartResolver are two implementations provided by spring framework for file uploading. By default there are no multipart resolvers configured but to use them for uploading files, all we need to define a bean named “multipartResolver” with type as MultipartResolver in spring bean configurations.
Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped HttpServletRequest. Then it’s used in the controller class to get the file and process it. For a complete example, please read Spring MVC File Upload Example.
Spring MVC Framework provides the following ways to help us achieving robust exception handling.
Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.
For a complete example, please read Spring Exception Handling Example.
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.
For Spring MVC applications, we can define multiple spring context configuration files through contextConfigLocation. This location string can consist of multiple locations separated by any number of commas and spaces. For example;
<servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,/WEB-INF/spring/appServlet/servlet-jdbc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
We can also define multiple root level spring configurations and load it through context-param. For example;
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/root-security.xml</param-value> </context-param>
Another option is to use import element in the context configuration file to import other configurations, for example:
<beans:import resource="spring-jdbc.xml"/>
ContextLoaderListener is the listener class used to load root context and define spring bean configurations that will be visible to all other contexts. It’s configured in web.xml file as:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
For creating a simple Spring MVC application, we would need to do the 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.
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.
The 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.
Spring provides excellent support for localization or i18n through resource bundles. Basis steps needed to make our application localized are:
Creating message resource bundles for different locales, such as messages_en.properties, messages_fr.properties etc.
Defining messageSource bean in the spring bean configuration file of type ResourceBundleMessageSource or ReloadableResourceBundleMessageSource.
For change of locale support, define localeResolver bean of type CookieLocaleResolver and configure LocaleChangeInterceptor interceptor. Example configuration can be like below:
Use spring:message element in the view pages with key names, DispatcherServlet picks the corresponding value and renders the page in corresponding locale and return as response.
<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <beans:property name="basename" value="classpath:messages" /> <beans:property name="defaultEncoding" value="UTF-8" /> </beans:bean> <beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> <beans:property name="defaultLocale" value="en" /> <beans:property name="cookieName" value="myAppLocaleCookie"></beans:property> <beans:property name="cookieMaxAge" value="3600"></beans:property> </beans:bean> <interceptors> <beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <beans:property name="paramName" value="locale" /> </beans:bean> </interceptors>
For a complete example, please read Spring Localization Example.
We can use Spring Framework to create Restful web services that returns JSON data. Spring provides integration with Jackson JSON API that we can use to send JSON response in restful web service.
We would need to do following steps to configure our Spring MVC application to send JSON response:
Adding Jackson JSON dependencies, if you are using Maven it can be done with following code:
Configure RequestMappingHandlerAdapter bean in the spring bean configuration file and set the messageConverters property to MappingJackson2HttpMessageConverter bean. Sample configuration will be:
In the controller handler methods, return the Object as response using @ResponseBody annotation. Sample code:
You can invoke the rest service through any API, but if you want to use Spring then we can easily do it using RestTemplate class.
<!-- Jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.databind-version}</version> </dependency>
<!-- Configure to plugin JSON as request and response in method handler --> <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <beans:property name="messageConverters"> <beans:list> <beans:ref bean="jsonMessageConverter"/> </beans:list> </beans:property> </beans:bean> <!-- Configure bean to convert JSON to POJO and vice versa --> <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> </beans:bean>
@RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET) public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) { logger.info("Start getEmployee. ID="+empId); return empData.get(empId); }
For a complete example, please read Spring Restful Webservice Example.
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, so you should go through Spring MVC RequestMapping Annotation Examples
@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, @Pointcut etc.
Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.
Spring provides built-in support for uploading files through MultipartResolver interface implementations. It’s very easy to use and requires only configuration changes to get it working. Obviously we would need to write controller handler method to handle the incoming file and process it. For a complete example, please refer Spring File Upload Example.
Spring supports JSR-303 annotation based validations as well as provide Validator interface that we can implement to create our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required validations.
For custom validator implementation, we need to configure it in the controller class. For a complete example, please read Spring MVC Form Validation Example.
Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandle, postHandle and afterCompletion.
We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.
We need to configure interceptors in the spring bean configuration file. We can define an interceptor to intercept all the client requests or we can configure it for specific URI mapping too. For a detailed example, please refer Spring MVC Interceptor Example.
Spring Framework provides excellent integration with JDBC API and provides JdbcTemplate utility class that we can use to avoid bolier-plate code from our database operations logic such as Opening/Closing Connection, ResultSet, PreparedStatement etc.
For JdbcTemplate example, please refer Spring JDBC Example.
For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then inject it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database operations.
Sample configuration would be:
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/> </beans:bean>
For complete example, please refer Spring Tomcat JNDI Example.
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 the 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>
Spring DAO support is provided to work with data access technologies like JDBC, Hibernate in a consistent and easy way. For example we have JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupport and JpaDaoSupport for respective technologies.
Spring DAO also provides consistency in exception hierarchy and we don’t need to catch specific exceptions.
We can use Spring ORM module to integrate Spring and Hibernate frameworks if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration.
Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for Hibernate boiler-plate code for transaction management.
For better understanding you should go through following tutorials:
Spring Hibernate Integration Example
Spring MVC Hibernate Integration Example
Spring security framework focuses on providing both authentication and authorization in java applications. It also takes care of most of the common security vulnerabilities such as CSRF attack.
It’s very beneficial and easy to use Spring security in web applications, through the use of annotations such as @EnableWebSecurity. You should go through the following posts to learn how to use the Spring Security framework.
Spring Security in Servlet Web Application
Spring MVC and Spring Security Integration Example
We need to define propertyConfigurer bean that will load the properties from the given property file. Then we can use Spring EL support to inject properties into other bean dependencies. For example;
<bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="location" value="/WEB-INF/application.properties" /> </bean> <bean class="com.journaldev.spring.EmployeeDaoImpl"> <property name="maxReadResults" value="${results.read.max}"/> </bean>
If you are using annotation to configure the spring bean, then you can inject property like below.
@Value("${maxReadResults}") private int maxReadResults;
Spring Framework is using a lot of design patterns, some of the common ones are:
Singleton Pattern: Creating beans with default scope.
Factory Pattern: Bean Factory classes
Prototype Pattern: Bean scopes
Adapter Pattern: Spring Web and Spring MVC
Proxy Pattern: Spring Aspect Oriented Programming support
Template Method Pattern: JdbcTemplate, HibernateTemplate etc
Front Controller: Spring MVC DispatcherServlet
Data Access Object: Spring DAO support
Dependency Injection and Aspect Oriented Programming
Some of the best practices for Spring Framework are:
Avoid version numbers in schema reference, to make sure we have the latest configs.
Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
For application-level properties, the best approach is to create a property file and read it in the spring bean configuration file.
For smaller applications, annotations are useful but for larger applications, annotations can become a pain. If we have all the configuration in XML files, maintaining it will be easier.
Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that get usually added when you create projects through Spring Tool Suite templates.
If you are using Aspects, make sure to keep the join pint as narrow as possible to avoid advice on unwanted methods. Consider custom annotations that are easier to use and avoid any issues.
Use dependency injection when there is an actual benefit, just for the sake of loose-coupling don’t use it because it’s harder to maintain.
That’s all for Spring Framework interview questions. I hope these questions will help you in coming Java EE interview. I will keep on adding more questions to the list as soon as I found them. If you know some more questions that should be part of the list, make sure to add a comment for it and I will include it
0 notes
Text
Spring Framework In Depth (2017)
Spring is an application framework and inversion-of-control (IOC) container for the Java platform. The framework’s core features can be used by any Java application and are ideal for enterprise and internet-based app development. Get a comprehensive overview of Spring, in this intermediate-level course with software architect Frank Moley. Frank develops applications and web services with Spring, and shares what he knows about configuring the ApplicationContext (the interface for accessing components, loading files, publishing events, and more), as well as the beans (objects within the Spring IOC container). He demonstrates a modern Java configuration workflow, as well as XML configuration for legacy software. He explores the Spring lifecycle in depth, so you can extend the framework and better troubleshoot any issues you have with your applications. Plus, learn how to use aspect-oriented programming to add behaviors to your apps in a reusable way.
Topics include:
Introduction to Spring Configuring the ApplicationContext Using the Spring expression language Configuring proxies Autowiring beans Using lifecycle methods Configuring beans with XML Understanding the initialization phases of the bean lifecycle Aspect-oriented programming and Spring
Duration: 2h 16m Author: Frank P Moley III Level: Intermediate Category: Developer Subject Tags: Web Web Development Software Tags: Spring Framework Spring ID: 2a6b0698b1d5996a5a517abb1a7db69f
Course Content: (Please leave comment if any problem occurs)
Welcome
The post Spring Framework In Depth (2017) appeared first on Lyndastreaming.
source https://www.lyndastreaming.com/spring-framework-in-depth-2017/?utm_source=rss&utm_medium=rss&utm_campaign=spring-framework-in-depth-2017
0 notes
Text
applicationContext-encryptanddecode.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<bean id="EncryptAndDecodeAspect" class="com.masterprojectoriginal.utils.EncryptAndDecodeUtil" /> <bean id="adminService" class="com.masterprojectoriginal.service.impl.AdminServiceImpl" /> <bean id="memberService" class="com.masterprojectoriginal.service.impl.MemberServiceImpl" /> <aop:config> <aop:pointcut expression="execution(* com.masterprojectoriginal.service.AdminService.findAdmin(..))" id="adminPointcut1"/> <aop:pointcut expression="execution(* com.masterprojectoriginal.service.MemberService.findMember(..))" id="memberPointcut1"/> <aop:pointcut expression="execution(* com.masterprojectoriginal.service.MemberService.findMemberById(..))" id="memberPointcut2"/> <aop:pointcut expression="execution(* com.masterprojectoriginal.service.MemberService.insert*(..))" id="memberPointcut3"/> <aop:pointcut expression="execution(* com.masterprojectoriginal.service.MemberService.update*(..))" id="memberPointcut4"/> <aop:aspect ref="EncryptAndDecodeAspect"> <aop:before method="shaEncrypt" pointcut-ref="adminPointcut1"/> <aop:before method="desEncrypt" pointcut-ref="memberPointcut1"/> <aop:before method="desEncrypt" pointcut-ref="memberPointcut3"/> <aop:before method="desEncrypt" pointcut-ref="memberPointcut4"/> <aop:after-returning method="desDecrypt" pointcut-ref="memberPointcut2" returning="result"/> </aop:aspect> </aop:config>
</beans>
0 notes
Text
interview
ng-disabled directive angularjs - Google Search
www.google.com
4:24 PM
AngularJS | ng-disabled Directive - GeeksforGeeks
www.geeksforgeeks.org
4:23 PM
loop and through dom angular - Google Search
www.google.com
4:22 PM
ng app optional - Google Search
www.google.com
4:22 PM
$dirty angularjs - Google Search
www.google.com
4:21 PM
ngsubmit ngclick not on same form - Google Search
www.google.com
4:21 PM
AngularJS: API: ngSubmit
docs.angularjs.org
4:20 PM
ngsubmit vs click - Google Search
www.google.com
4:20 PM
angularjs - differences between ng-submit and ng-click - Stack Overflow
angular how do format view in form dollars - Google Search
www.google.com
4:20 PM
Angular - CurrencyPipe
angular.io
4:18 PM
angular rootscope vs scope - Google Search
www.google.com
4:18 PM
angular two way binding - Google Search
www.google.com
4:18 PM
Angular Data Binding
www.w3schools.com
4:18 PM
Angular - Two-way binding [(...)]
angular.io
4:17 PM
angular delimiter html modal - Google Search
www.google.com
4:16 PM
angular delimiter html modal - Google Search
www.google.com
4:16 PM
angular delimiter - Google Search
www.google.com
4:16 PM
angular.extend - Google Search
www.google.com
4:16 PM
AngularJS: API: angular.extend
docs.angularjs.org
4:15 PM
angularjs isolate scope - Google Search
4:15 PM
angularjs isolate scope - Google Search
www.google.com
4:15 PM
AngularJS: Developer Guide: Directives
docs.angularjs.org
4:15 PM
AngularJS: Developer Guide: Directives
docs.angularjs.org
4:15 PM
AngularJS - Understanding Isolate Scope - Thinkster
thinkster.io
4:15 PM
angular js tough problem - Google Search
www.google.com
4:14 PM
29 AngularJS Interview Questions and Answers You Should Know
spring aop - Google Search
www.google.com
4:12 PM
spring bean factory - Google Search
www.google.com
4:12 PM
Chapter 3. Beans, BeanFactory and the ApplicationContext
docs.spring.io
4:11 PM
spring boot actuator - Google Search
www.google.com
4:11 PM
spring initializr - Google Search
www.google.com
4:11 PM
custom spring boot auto configuration starter - Google Search
www.google.com
4:10 PM
spring boot starter project - Google Search
www.google.com
4:10 PM
Getting Started | Building an Application with Spring Boot
spring.io
4:10 PM
spring boot starter - Google Search
www.google.com
4:09 PM
spring dependency injection scope - Google Search
www.google.com
4:09 PM
4.4 Bean scopes
docs.spring.io
4:09 PM
spring dependency injection - Google Search
www.google.com
4:08 PM
Dependency Injection with the Spring Fra
static in java - Google Search
www.google.com
4:07 PM
static in java - Google Search
www.google.com
4:07 PM
while vs do while java - Google Search
www.google.com
4:06 PM
copy entire object java - Google Search
www.google.com
4:06 PM
lambda expressions java - Google Search
www.google.com
4:05 PM
default method in functional interface - Google Search
www.google.com
4:05 PM
functional interface - Google Search
www.google.com
4:05 PM
functional interface - Google Search
www.google.com
4:04 PM
java method reference - Google Search
www.google.com
4:04 PM
java reference - Google Search
www.google.com
comparator vs comparable - Google Search
www.google.com
4:02 PM
list vs set vs map - Google Search
www.google.com
4:02 PM
list vs set - Google Search
www.google.com
4:02 PM
.equals vs == string - Google Search
wcomparator vs comparable - Google Sea
interface vs abstract class java - Google Search
www.google.com
4:01 PM
java stringbuilder vs string concatenation performance - Google Search
0 notes
Text
Here are all the reasons to choose Spring Boot over Spring Framework!
Why Choose Spring Boot over Spring Framework?
Let’s get started with some basics of Spring framework as well as Spring Boot!
Spring is a popular Java based framework to build web and enterprise applications. Spring Framework provides a wide variety of features that address the modern business needs. Spring Framework gives flexibility to configure beans in multiple ways like XML, Annotations and JavaConfig. As the number of features increased so did complexity. Task of spring application configuration became tedious and error-prone.
Spring team created Spring Boot to address the configuration complexity.
Spring Boot is not here to compete with Spring or Spring MVC, on the contrary it makes it easier to use them.
Spring Boot makes it easy to develop Spring-powered, production grade applications and services with minimum hassle. It narrows down Spring platform so that new or existing users can quickly get to the required bits. What’s more! Spring Boot makes it easy to build stand alone, production-grade Spring based Applications that can be “just run”.
Let’s Skim Through Some of the Noteworthy Features
ü Stand alone application development
ü Embedded Tomcat, Jetty or Undertow
ü Provides narrow ‘starter’ dependencies to simplify your build configuration
ü Auto configuration of Spring and 3rd party libraries wherever possible
ü Renders production ready features such as metrics, health checks, and external configuration
ü No code generation or XML configuration
Modules
Here is a quick overview of modules for you to understand Spring Boot better!
Spring Boot
Main library provides features that support other parts of Spring Boot, they include:
1. The SpringApplication class, rendering static convenience methods that makes it easy to create a stand alone application. Its only work is to create and refresh an appropriate Spring ApplicationContext.
2. A choice of container for Embedded web applications
3. Externalized Configuration Support
4. ApplicationContext initializers that include support for sensible logging defaults
Spring-boot-auto configuration
Spring Boot can configure sizeable parts of common applications based on content of their classpath. A single @EnableAutoConfiguration annotation activates auto configuration of Spring Context. Auto configuration tries to deduce which beans a user might need. Moreover, auto configuration will always back down when the user starts to define their own beans.
Spring-boot-Starters
Spring Boot starters are a set of convenient dependency descriptors that can be included in the application. It’s a one stop shop for all Spring related technology which you need without having to go through the hassle of copy pasting loads of dependency descriptors.
Spring-Boot-cli
Spring command line application compiles and runs Groovy source, making it absolutely easy to write minimal code to get the application running. Furthermore, it can also watch files automatically recompile and restart when they change.
Spring-Boot-Actuator
Actuator endpoints allow you to monitor and interact with your application. Spring boot actuator furnishes the infrastructure required for actuator endpoints. This module being out of the box provides a number of endpoints including HealthEndpoint, EnvironmentEndpoint, BeansEndpoints etc.
Spring-Boot-Actuator-autoconfigure
This module provides auto configuration for actuator endpoints depending on content of classpath and a set of properties. It includes configuration to expose endpoints over HTTP or JMX. It will back down as soon as the user starts to define their own beans just like Spring Boot AutoConfigure.
Spring-Boot-Test
This module comprises core items and annotations that can be helpful for testing your application.
Spring-Boot-Test-Autoconfigure
This module, like other Spring Boot auto configuration modules, provides auto configuration for tests on the basis of classpath. It contains a number of annotations to automatically configure a slice of the application that needs to be tested.
Spring-Boot-Loader
It renders the secret sauce which allows you to build a single jar file that can be launched using java-jar. Generally, you need not use this module directly, but instead with the Gradle or Maven plugin.
Spring-Boot-Devtools
The module provides additional development-time features like automatic restarts for a smooth application development experience. Developer tools are disabled while running a full packaged application.
After all the information given above, the question remains Why Opt for Spring Boot?
Here are some convincing reasons for you to take a well informed decision!
Auto Configuration
Spring and Spring MVC applications have a lot XML or Java Bean Configuration to carry out. Spring Boot has brought about a new thought process around this.
How about auto-configuring a Data source when Hibernate jar is on classpath?
How about auto-configuring a Dispatcher Servlet when Spring MVC jar is on classpath?
There may be provisions to override the default auto configuration. Spring Boot looks at frameworks available on the classpath and existing configuration for the application. It furnishes basic configuration needed to configure the application with these frameworks based on the above information. This is called Auto configuration.
Spring Boot Starter Projects
While developing a web application, you need to identify the frameworks to be used, versions of those framework and more importantly how to connect them. According to documentation, starters are set of convenient dependency descriptors that can be included in your application. It’s a one-stop-shop for all Spring related technology that is needed.
For instance, let’s consider Spring Boot Starter Web. If you want to develop a web application or an application to expose restful services, Spring Boot Starter Web is the perfect option. You can create a quick project using Spring Initializr.
Any typical web application will use the following dependencies:
Ø Spring - core, beans, context, aop
Ø Web MVC - Spring MVC
Ø Jackson - for JSON Binding
Ø Validation - Hibernate Validator, Validation API
Ø Embedded Servlet Container - Tom cat
Ø Logging - logback, slf4j
What’s interesting here? Spring Boot Starter Web has all these dependencies pre packaged. A developer need not worry about these dependencies or their compatible versions.
Simplified Higher Level Abstractions
One of the primary goals of Spring Boot is to make everything easier.
Spring portfolio has its own strong Web MVC framework, Spring Security framework but its other projects majorly aim to provide higher level abstractions to make their use easier.
For illustration, Spring Data JPA makes the use of JPA easy by providing APIs to perform CRUD operations, Sorting and Pagination without the requirement to implement them yourself. Spring AMPQ or Spring for Kafka renders higher level of abstractions for you to work easily with RabbitMQ or Kafka without writing low-level boilerplate code.
Micro-services and Cloud Native Friendly
The latest trend now is the microservice architecture and organizations prefer their deployment in Cloud environments such as AWS, CloudFoundry etc.
Generally, Spring Boot applications are developed as self-contained deployment units and by using its Profiles concept, the same application can be deployed in multiple environments without any changes in code.
Moreover, SpringCloud modules provide an amazing set of features necessary to build Cloud Native microservices.
Addresses Modern Enterprise Needs
Requirements of modern enterprise applications are changing constantly and rapidly. Waiting for 3-4 years release cycle to get new features is not feasible. Frameworks with rapid release cycles are required to support business needs.
At its core, Spring is just a Dependency Injection container.
But the actual power of Spring is its rich set of portfolio projects. Be it using NoSQL databases, wanting a robust Security Framework, integration with Social platforms, Big Data Frameworks or streaming platforms like Kafka, everything is taken care of.
Was the article helpful? Visit www.kodytechnolab.com now to hire Spring Boot services for your next project!
0 notes
Text
Spring Digging Road 1 - Basic introduction of Spring framework
## Spring Brief Introduction
Spring is an open source framework, which was first created by Rod Johnson. It solves the problem of loose coupling between business logic layer and other layers. At the beginning of its birth, the main graveyard of Spring was to replace the more heavyweight enterprise Java technology, especially EJB. Compared with EJB, Spring provides a lighter and simpler programming model.
After decades of development, Spring is expanding into other fields, such as mobile development, social API integration, NoSQL database, cloud computing, big data and micro-service architecture.
### Four strategies adopted by Spring to simplify development:
> Lightweight and minimally invasive programming based on POJO(POJO)
>
> Loose coupling through dependency injection and interface orientation(IOC)
>
> Declarative programming based on cuts and conventions(AOP)
>
> Reduce boilerplate code through cuts and templates(Template)
#### Spring--Lightweight and minimally invasive programming based on POJO
Many frameworks force applications to inherit the specified classes or implement the specified interfaces, so as to realize the corresponding functions, which leads to the forced coupling between applications and frameworks.
Spring does not force the implementation of the interface of Spring specification or the class that inherits the specification. On the contrary, in the application built based on Spring framework, its class usually has no trace that Spring has been used. The worst-case scenario is to use Spring annotations, but it is still a simple POJO class that can do anything else.
#### Spring--Loose coupling through dependency injection and interface orientation
Class A depends on class B, and must use B's instance, so:
>1.Pass in class B through the interface of class A.{(A implements B) => A}
>
>2.Pass B in through the constructor of class A{(new A(B)) => A}
>
>3.Pass B in by setting the properties of class A{new A().setB(B) => A}
This process is called dependency injection(DI)
#### Spring--Declarative programming based on cuts and conventions
IOC can keep the cooperative software components loosely coupled, while AOP allows **to separate the functions all over the system to form reusable components**.
Aspect-oriented programming is often defined as a separation technology that promotes software systems to realize concerns. The system consists of many different components, each of which is responsible for a specific function. In addition to implementing their core functions, these components often take on additional responsibilities. System services, such as log, transaction management and security, are often integrated into components with core business logic. These system services are usually regarded as crosscutting concerns because they span multiple components of the system.
If these concerns are dispersed among multiple components, the code will bring double complexity.
>**The code that implements the system focus function will appear repeatedly in multiple components**
>
>**Components get confused by code that has nothing to do with their core business**
#### Spring--Reduce boilerplate code through cuts and templates
When coding, in order to achieve common and simple tasks, it is necessary to write similar codes over and over again, which is called boilerplate code. A common example of template code is to use JDBC to access database to query data. It is also common that JSM, JNDI and REST services also involve a large number of duplicate codes
>**Spring aims to eliminate boilerplate code through template encapsulation**
### Spring Container
In Spring-based applications, **application objects are located in the Spring container**, which is responsible for creating, assembling, configuring and managing the life cycle of objects from birth to death.
Spring container uses IOC to manage the components that make up the application, and it will create the association between the components that cooperate with each other. Make these objects simpler, cleaner, easier to understand, easier to reuse and easier to carry out unit testing.
There is not only one container, but Spring comes with several container implementations, which can be classified into two different types.
>Bean factory (defined by org.springframework.beans.factory.beanfactory interface) is the simplest container and provides basic DI support.
BeanFactory:Provides the basic dependency injection function, and when a bean object is called, it will be instantiated (delayed loading form)
>The context of application (defined by org. springframework.context.applicationcontext interface) **is built based on** BeanFactory and provides application framework level services
ApplicationContext:Higher-level context objects built on BeanFactory are more powerful than BeanFactory. Loaded when the container is started (all objects will be instantiated when the container is started)
```
ClassPathXmlApplicationContext:Load configuration file build context from classpath
FileSystemXmlApplicationContext:Load configuration file build context from file system
XmlWebApplicationContext:Build context from the configuration file loaded in the web system
```
**PS: Bean factory is often too low-level for most applications, so application context is more popular than Bean factory**
### The life cycle of Bean
In traditional Java applications, the life cycle of a bean is very simple, and the bean can be used after being instantiated by Java keywords such as new and reflection. Once the bean is no longer used, it will be automatically garbage collected by Java virtual machine. By contrast, the life cycle of bean in Spring container is much more complicated.
>1.Spring instantiates bean;
>
>2.Spring injects values and bean references into the bean's corresponding properties;
>
>3.If the bean implements the BeanNameAware interface, Spring passes the bean's ID to the setBeanName () method;
>
>4.If the bean implements the BeanFactoryAware interface, Spring will call the setBeanFactory () method to pass in the BeanFactory container instance;
>
>5.If the bean implements the ApplicationContext interface, Spring will call the setApplicationContext () method to pass in the reference of the ApplicationContextAware the bean is located;
>
>6.If bean implement the BeanPostProcessor interface, Spring will call their post-ProcessBeforeInitialization() method;
>
>7.If beans implement the Initializing bean interface, Spring will call their after-PropertiesSet () method. Similarly, if a bean declares an initialization method using init-method, the method will also be called;
>
>8.If bean implement the BeanPostProcessor interface, Spring will call their post-ProcessAfterInitialization() method;
>
>9.At this point, the bean are ready to be used by the application, and they will stay in the application context until the application context is destroyed;
>
>10.If the bean implements the DisposableBean interface, Spring will call its destroy () interface method. Similarly, if a bean declares a destruction method using the destory-method, the method will also be called.
0 notes
Text
Learning Spring
Since most of my programming experience is in Java, I decided I might try learning to build a project using the Spring framework. I’ve been trying to follow a few different Spring tutorials (the ones that I don’t have to pay), but I think some of them might be outdated. Right now it’s August 2018, and I’m currently going through the tutorial at https://www.javatpoint.com/spring-tutorial.
Setting Up the Project: I was a little confused about how to set up the project at first. I wanted to directly download the Spring .jar files from the original website, but I couldn’t find them there. I found an answer on StackOverflow that using Maven might be a good idea. I already have Eclipse on my PC and it includes Maven, so I followed the example at http://www.vogella.com/tutorials/EclipseMaven/article.html to create the project. In the pom.xml file I added the dependencies:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.1.2.RELEASE</version> <scope>runtime</scope> </dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency>
The tutorial said to use org.springframework.beans.factory.xml.XmlBeanFactory, but evidently this is deprecated. I looked at an answer on StackOverflow to do the following:
ApplicationContext factory = new ClassPathXmlApplicationContext([insert xml file]);
instead of the XmlBeanFactory. Also, the program continued to throw an error because the String I used for the xml file was incorrect. So I either had to use “src/main/java/filename.xml” or “classpath:filename.xml” to fix the error.
I’ll write more when I have more problems.
0 notes
Text
Autowiring
The Spring container can autowire relationships between collaborating beans. You can allow Spring to resolve collaborators (other beans) automatically for your bean by inspecting the contents of the ApplicationContext. Autowiring has the following advantages:
Autowiring can significantly reduce the need to specify properties or constructor arguments.
Autowiring can update a configuration as…
View On WordPress
0 notes
Text
Inversion of Control container in Spring
Inversion of Control container in Spring
Previously we talked about what the Difference between BeanFactory and ApplicationContext, and How Spring works at a glance. Therefore in this article, we go deeper into what is the Inversion of Control container in Spring and how it works?
What is Inversion of Control container in Spring and how it works? The Inversion of Control (IoC)
In objected oriented programming it all about to remove the…
View On WordPress
0 notes