Spring Review 05012022
What is HTTP?
Hypertext Transfer (or Transport) Protocol, the data transfer protocol used on the World Wide Web.
What HTTP verb is used to send a request to a SOAP service?
POST
What are Bean scopes?
1. singleton (default): single instance per Spring container 2. prototype: can have any number of object instances 3. request: scopes to HTTP request (application context must be web-aware) 4. session: scopes to HTTP session (application context must be web-aware) 5. global-session: scopes to global HTTP session (application context must be web-aware)
What is a Pointcut?
@Pointcut declares the pointcut expression. Pointcut is a set of one or more JoinPoint where an advice should be executed. You can specify Pointcuts using expressions or patterns as we will see in our AOP examples. In Spring, Pointcut helps to use specific JoinPoints to apply the advice.
How is a Controller different from a RestController?
@RestController is just a convenience annotation that combines @Controller and @ResponseBody. the @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.
What is point to point communication?
A point-to-point connection is a permanent direct communication link between two parties. Unlike a dial-up connection, it does not need to be established via dial-up or disconnected following communication.
How would you test your web services?
1)Understand the WSDL file. 2)Determine the operations that particular web service provides. 3)Determine the XML request format which we need to send. 4)Determine the response XML format. 5)Using a tool or writing code to send request and validate the response.
What are some of the different implementations of the Application Context? When do we use them?
1. AnnotationConfigApplicationContext: constructor accepts one or more classes annotated with @Configuration or @Component. (ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class)) 2. AnnotationConfigWebApplicationContext: same as above, but this class must be registered and then instantiated and injected to DispatcherServlet by implementing WebApplicationInitializer. (AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(AppConfig.class); context.setServletContext(container);) 3. XmlWebApplicationContext: sets an XMLfile as configuration, must be injected to servlet like above 4. FileSystemXmlApplicationContext: sets an XML file from file system or URL as configuration 5. ClassPathXmlApplicationContext: sets an XML file from the classpath as configuration
What are some of the AspectJ annotations? What do they do?
@Before: It runs before the method execution. @AfterReturning: It runs after the result is returned by the method. @AfterThrowing: It runs after an exception is thrown by the method. @After(Finally): It is executed after method execution or after an exception is thrown or the result is returned by the method. @Around: It can perform the behavior before and after the method invocation. @Pointcut: Pointcut is a signature that matches the join points.
List some of the annotations used in Spring MVC. What are they used for?
@Controller: indicates a controller (stereotype) @RequestMapping: maps URLS onto a class or handler method @PathVariable: binds a method argument to the value of a URI template variable @RequestParam: binds request parameters to method variables @ModelAttribute: indicates the argument should be retrieved from the model (if not present, should be added)
What are some of the AspectJ annotations? What do they do?
@Before declares the before advice. It is applied before calling the actual method. @After declares the after advice. It is applied after calling the actual method and before returning result. @AfterReturning declares the after returning advice. It is applied after calling the actual method and before returning result. But you can get the result value in the advice. @Around declares the around advice. It is applied before and after calling the actual method. @AfterThrowing declares the throws advice. It is applied if actual method throws exception.
What are some of the tags used in the ApplicationContext.xml?
<beans> (contains beans) <bean id="" class=""> (defines bean) <constructor-arg name="" ref=""> (injects bean into constructor argument) <property name=""> (within bean, contains value) <value> (defines value of property) (ref must refer to a bean's id)
What is AspectJ?
@AspectJ refers to a style of declaring aspects as regular Java classes annotated with annotations. The @AspectJ style was introduced by the AspectJ project as part of the AspectJ 5 release. Spring interprets the same annotations as AspectJ 5, using a library supplied by AspectJ for pointcut parsing and matching.
What are some of the other annotations available in Spring?
@Autowired: enables auto-wiring of beans @Transactional: configures transactions @Scope: lets you change a component's scope (default is singleton) @Bean: indicates a factory method (that instantiates a Spring bean); MUST be in a @Configuration class @Value: injects property values into beans (compatible with constructor, setter, and field injection)
What are some Spring stereotypes? What are they used for?
@Service: indicates business logic @Repository: indicates CRUD operations; usually used with DAO (data access object) or repository implementations that deal with database tables @Controller: indicates handling of user requests and returning appropriate response (usually used with REST web services) These annotations are functionally identical to @Component. They only mark classes for human readability.
What does a SOAP message look like?
A SOAP message is an ordinary XML document containing the following elements − Envelope − Defines the start and the end of the message. It is a mandatory element. Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element. Body − Contains the XML data comprising the message being sent. It is a mandatory element. Fault − An optional Fault element that provides information about errors that occur while processing the message.
What is a controller?
A controller is responsible for controlling the way a user interacts with an MVC application. It handles any incoming URL request and determines the response to send back to the user.
What is a messaging queue?
A message queue provides a lightweight buffer which temporarily stores messages, and endpoints that allow software components to connect to the queue in order to send and receive messages. The messages are usually small, and can be things like requests, replies, error messages, or just plain information.
What is a web service?
A web service is a software system that supports interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically, web Service Definition Language, or WSDL). web services fulfill a specific task or a set of tasks.
How does Spring AOP allow you to modularize concerns?
AOP weaves cross-cutting concerns into the classes, without making a call to the cross-cutting concerns from those classes by making it easy to maintain and make changes to the aspects and you only need to make changes in one place.
What is an aspect?
Aspect: An aspect is a class that implements enterprise application concerns that cut across multiple classes, such as transaction management. Aspects can be a normal class configured through Spring XML configuration or we can use Spring AspectJ integration to define a class as Aspect using @Aspect annotation.
What is Bean wiring? How do explicitly wire a bean in? Autowire a bean?
Bean wiring is creating associations between Spring Beans with dependency injection. To explicitly wire a bean, you must use XML configuration and set one bean's property ref to another bean's id. To autowire a bean, you can use the @Autowired annotation, as long as it lies within the configured ComponentScan directories.
What is the Spring Bean life cycle?
Beans are first instantiated. Their properties are set. Any associated interfaces or objects are made aware of their existence. The bean is made aware of any associated interfaces as well. Any other methods, particularly custom created methods, are invoked. Then the bean is ready for use. Once the bean is no longer used, it is marked for removal and a destroy method is invoked for the bean Custom destroy methods are invoked, if any. Bean is the destroyed.
What are some of the modules of Spring? What do they help you achieve?
Core & Beans: These modules provide the fundamental framework for springs IoC container, including dependency injection features. Beans specifically feature the BeanFactory, which is a sophisticated implementation of the factory design pattern used to create beans, which are used in dependency injection. Context: This modules builds off from the core and bean modules used for more enterprise functionality. The main feature, ApplicationContext represents the Spring IoC container and is used to instantiate, onfigure and assemble beans. SpEL (Spring Expression Language): A module which provides a powerful expression language which can be used to query and manipulate an object graph at runtime, including setting and getting property values, property assignment, method invocation, accessing array content, collections and indexer and more. Data Access/Integration The Data Access/Integration layer provides support for database management or layers of abstraction for ease of use. JDBC (Java Database Connectivity): A module which provides a layer of abstraction for JDBC ORM (Object Relational Mapping): A module which provides integration layers for ORM APIs, such as JPA, JDO and Hibernate OXM (Object/XML Mapping): A module which provides a layer of abstraction for mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream JMS (Java Messaging System): A module which provides feature to produce and consume messages. Transaction: A module which provides programmatic and declarative support for transaction management in classes that implement special interfaces as well as POJOs Web The Web layer provides basic web integration features for an application. Web-Servlet: A module which provides an implementation for Spring MVC, a clean separation between model code and web forms, and also integrates with other features of the Spring framework. WebSocket: A module which provides a standardized way to esablish a communication channel between a client and server with a single TCP connection. Web-Portlet: A module incredibly similar to the servlet workflow, that is marked by two distinct phases, an action phase, which is executed once when any backend changes occur, and a render phase, in which information is displayed to the user.
What are the different approaches to dependency injection in Spring?
Dependency Injection can occur through the following methods: Constructor Injection: Dependency Injection accomplished when the container invokes a constructor with arguments to instantiate a bean in which each argument of said constructor represents a dependency. Setter Injection: Dependency Injection accomplished when the container calls setter methods on a bean after invoking a no-argument constructor to instatiate a bean.
What is dependency injection?
Dependency Injection is a design pattern that removes dependencies of a program by providing the configuration in an external source, such as an XML file. This loosely coupled design then makes code easier to test, and implement in a wider variety of environments.
What is the name of the only servlet used in Spring MVC? How do you configure it?
DispatcherServlet needs to be declared and mapped according to the Servlet specification by using Java configuration (register web context, create servlet, register it, add mapping) or in web.xml.
How do I expose/consume REST? SOAP?
Expose Your Application With a REST API Step One - Define API Interactions. Rental Listing Example. Step Two - Identify Resources. Resources. ... Step Three - Define Message Format. ... Step Four - Define Endpoints. ... Step Five - Implement Endpoints. ... Step Six - Document Your API. Step Seven - Publish Your API. The steps involved in exposing a SOAP web service as a REST API are summarized as follows: Virtualize the SOAP web service. Define a new REST API. Route all REST requests through the virtualized SOAP service. Test the REST to SOAP mapping.
What is HTTP?
HTTP is a protocol for fetching resources such as HTML documents. It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser.
What is HTTP?
HTTP, in full HyperText Transfer Protocol, standard application-level protocol used for exchanging files on the World Wide Web. HTTP runs on top of the TCP/IP protocol and (later) on the QUIC protocol.
What is the HandlerMapping interface?
HandlerMapping is an interface that defines a mapping between requests and handler objects. This can be implemented to provide customized mapping strategy, if the Spring MVC's ready-made implementations are insufficient.
What are some different types of advice?
In Spring AOP, 4 type of advices are supported : Before advice - Run before the method execution. After returning advice - Run after the method returns a result. After throwing advice - Run after the method throws an exception. Around advice - Run around the method execution, combine all three advices above.
What is the IOC container/Application Context?
In Spring, the IoC Container is responsible for instantiating, configuring and assembling objects known as beans. It does this by getting information from the XML file and assembling the objects accordingly. In Spring there are two types of IoC Containers, the BeanFactory and Application context, which is built out of the Bean factory. More information on BeanFactory, ApplicationContext and Beans can be found in the configuration lecture notes. The ApplicationContext interface is built on top of the BeanFactory with extra functionality, such as simple integration with Spring AOP, event propagation, message resource handling, and application layer specific context (such as WebApplicationContext for web applications).
What is a Pointcut?
In aspect-oriented programming, a pointcut is a set of join points. Pointcut specifies where exactly to apply advice, which allows separation of concerns and helps in modularizing business logic
What are the different HTTP status codes?
Informational responses ( 100 - 199 ) Successful responses ( 200 - 299 ) Redirection messages ( 300 - 399 ) Client error responses ( 400 - 499 ) Server error responses ( 500 - 599 )
What is Advice
It is the action taken by an aspect at a particular join-point. Joinpoint is a point of execution of the program, such as the execution of a method or the handling of an exception. In Spring AOP, a joinpoint always represents a method execution.
What is a Join Point? Proceeding Join Point?
JoinPoint = A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution. Join point information is available in advice bodies by declaring a parameter of type org.aspectj.lang.JoinPoint. ProceedingJoinPoint = an extension of the JoinPoint that exposes the additional proceed() method. When invoked, the code execution jumps to the next advice or to the target method. It gives us the power to control the code flow and decide whether to proceed or not with further invocations.
What is a Join Point? Proceeding Join Point?
JoinPoint is an AspectJ interface that provides reflective access to the state available at a given join point, like method parameters, return value, or thrown exception. It also provides all static information about the method itself. ex. @Before("articleListPointcut()") public void beforeAdvice(JoinPoint joinPoint) { log.info( "Method {} executed with {} arguments", joinPoint.getStaticPart().getSignature(), joinPoint.getArgs() ); } ProceedingJoinPoint is an extension of the JoinPoint that exposes the additional proceed() method. When invoked, the code execution jumps to the next advice or to the target method. It gives us the power to control the code flow and decide whether to proceed or not with further invocations. ex. @Around("articleListPointcut()") public Object aroundAdvice(ProceedingJoinPoint pjp) { Object articles = cache.get(pjp.getArgs()); if (articles == null) { articles = pjp.proceed(pjp.getArgs()); } return articles; }
What is the JPA Repository?
JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting.
What are some of the advantages of using Spring?
Light Weight: Spring is a lightweight framework because of its POJO implementation. It does not force the programmer to inherit any class and implement any interface. With the help of Spring, we can enable powerful, scalable applications using POJOs (Plain Old Java Object). Flexible: It provides flexible libraries trusted by developers all over the world. The developer can choose either XML or Java-based annotations for configuration options. The IoC and DI features provide the foundation for a wide-ranging set of features and functionality. It makes the job simpler. Loose Coupling: Spring applications are loosely coupled because of dependency injection. It handles injecting dependent components without a component knowing where they came from. Powerful Abstraction: It provides a powerful abstraction to JEE specifications such as JMS, JDBC, JPA, and JTA. Declarative Support: It provides declarative support for caching, validation, transaction, and formatting. Portable: We can use server-side in web/EJB app, client-side in swing app business logic is completely portable. Cross-cutting behavior: Resource management is a cross-cutting concern, easy to copy and paste everywhere. Configuration: It provides a consistent way of configuring everything, separate configuration from application logic, varying configuration. Lifecycle: Responsible for managing all your application components, particularly those in middle-tier container sees components through well-defined lifecycle: init(), destroy(). Dependency Injection: The use of dependency injection makes the easy development of JavaEE. Easier Testing: The use of dependency injection makes the testing easy. The spring framework does not require a server while the EJB and Struts application requires a server. Fast: The team of Spring engineers deeply cares about the performance. Its fast startup, fast shutdown, and optimized execution maintain performance make it fast. Even, we can start a new Spring project in seconds by using Spring Initializr. Secure: It monitors third-party dependencies closely. The regular update is issued that make our data and application secure. We can make our application secure by using the Spring Security framework. It provides industry-standard security schemes and delivers a trustworthy solution that is secure by default. Supportive: The Spring community provides support and resources to get you to the next level QuickStart guides, tutorials, videos, and meetup helps a lot. Productive: It is more productive because the spring application can integrate with other Spring-based applications. For example, we can combine the Spring Boot application with Spring Cloud
What is tight coupling? Loose coupling?
Loose coupling means that the degree of dependency between two components is very low. Tight coupling means that the degree of dependency between two components is very high.
What is Postman? ARC? SoapUI?
Postman is a great software tool for connecting and making test calls to RESTful APIs made by others or by yourself. ARC is a free, open source tool for testing APIs SoapUI is an open source tool for testing APIs in general. It allows users to execute automated functional, regression, compliance, and load tests on different Web APIs of all kinds and technologies including SOAP and REST.
What is Postman? ARC? SoapUI?
Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster. ARC- Advanced REST client allows you to test your APIs. Easy and clean user interface helps you focus on your API and not tooling. SoapUI is a cross-platform functional automation testing tool. SoapUI is free and open source tool and it has been designed to help test APIs such as SOAP and REST interfaces to ensure interoperability of different applications.
What is a topic? A queue?
Queues and Topics are similar when a sender sends messages, but messages are processed differently by a receiver. A queue can have only one consumer, whereas a topic can have multiple subscribers. In JMS a Topic implements publish and subscribe semantics. When you publish a message it goes to all the subscribers who are interested - so zero to many subscribers will receive a copy of the message. Only subscribers who had an active subscription at the time the broker receives the message will get a copy of the message. A JMS Queue implements load balancer semantics. A single message will be received by exactly one consumer. If there are no consumers available at the time the message is sent it will be kept until a consumer is available that can process the message. If a consumer receives a message and does not acknowledge it before closing then the message will be redelivered to another consumer. A queue can have many consumers with messages load balanced across the available consumers. So Queues implement a reliable load balancer in JMS.
What is REST? SOAP?
REST stands for REpresentational State Transfer. It means when a RESTful API is called, the server will transfer to the client a representation of the state of the requested resource. SOAP is an acronym for Simple Object Access Protocol. It is an XML-based messaging protocol for exchanging information among computers. SOAP is an application of the XML specification.
What is REST? What are the constraints of REST?
REST stands for Representational State Transfer. It means when a RESTful API is called, the server will transfer to the client a representation of the state of the requested resource. REST defines 6 architectural constraints which make any web service - a truly RESTful API. -Uniform interface. -Client-server. -Stateless. -Cacheable. -Layered system. -Code on demand (optional)
What might be present in an HTTP request? An HTTP Response?
Request - GET, PUT, POST Response - Status codes like 200, 404, 302. and a description of the status code to help people understand the message.
What is a Spring Bean?
Spring Beans are Java Objects that are initialized by the Spring IoC (inversion of control) container.
What are some of the Spring projects?
Spring Boot Spring Boot is one of the most popular frameworks for developing microservices today. Spring Boot makes it easy to develop applications quickly. It has important features such as starter projects, auto-configuration, and actuator; it is a cakewalk to develop microservices. Spring Cloud The world is moving more and more towards the cloud. Everyone wants to deploy their application in the cloud. If you develop a microservice using Spring Boot, you could use Spring Cloud to make it cloud-enabled. Spring Data Spring Data provides mechanisms for consistent data access. A few years earlier, there was only one kind of database that an application could connect to — the SQL-based relational databases. Today, we also have at our disposal a wide variety of databases including the NoSQL databases. Spring Data ensures that the way we access data from all these sources remains consistent. Spring Integration Spring Integration, on the other hand, addresses the issues of application integration. Spring Integration provides implementations for recommended architecture patterns in Enterprise Application Integration. Spring Batch Not all processing is done online, and a lot is also accomplished through batch applications. Batch applications have their own unique set of requirements. For instance, it is important to be able to restart a batch job from the point where it had failed earlier. It may also be necessary to track down accurately what is happening in the background when a batch job executes. Spring Batch provides a great option to develop batch applications. Spring Security Security is one of the most important non-functional requirements of an application's development. Any application that you develop, be it a web application, a REST service, or any other, you want it to be secure. Spring Security provides features for securing the applications that you develop. It has support for basic authentication, OAuth1, and OAuth2 authentication. Spring HATEOAS With RESTful services, it is not sufficient if you simply return the data for a resource. It is also recommended to return related actions you can perform on the resource. This is called HATEOAS. Spring HATEOAS enables you to develop HATEOAS compatible REST API.
What does the @SpringBootApplication annotation do? Which annotations does it rely on under the hood?
Spring Boot @SpringBootApplication annotation is used to mark a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It's same as declaring a class with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations
What is Spring Boot?
Spring Boot is an open source, microservice-based Java web framework. The Spring Boot framework creates a fully production-ready environment that is completely configurable using its prebuilt code within its codebase.
What version(s) of Spring are we using?
Spring Core/Context/Web 5.3.19
What is Spring Data JPA?
Spring Data JPA provides a framework that works with JPA and provides a complete abstraction over the Data Access Layer. Spring Data JPA brings in the concept of JPA Repositories, a set of Interfaces that defines query methods. The Repository and Entity Bean represent the DAO layer in the application.
What is Spring JMS?
Spring provides a JMS integration framework that simplifies the use of the JMS API much like Spring's integration does for the JDBC API. JMS can be roughly divided into two areas of functionality, namely the production and consumption of messages.
What was the old IOC container in Spring? How does it differ from the current IOC container?
The Spring Bean Factory interface establishes the underlying basis for the Spring IoC Container functionality by providing advanced configurations capable of managing any type of object. The ApplicationContext is a sub-interface of the BeanFactory interface which adds easier integration with Spring's AOP features. This ApplicationContext represents the Spring IoC container as it is responsible for the instantiation, assembly and management of "beans". These "Beans", are the term used for objects created in Spring which form the backbone of an application. Though they are created and managed by the IoC Container, they are otherwise just a type of object in an application. When bean objects have certain dependencies, these are reflected within configuration metadata used by the container. In other words, the BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext adds more enterprise-specific functionality for to the creation and management of objects in the Spring framework.
What is the Spring Framework?
The Spring Framework is an application framework and inversion of control container for the Java platform. It provides flexible infrastructural support to create loosely coupled Java applications by utilizing dependency injection. These spring frameworks provide a comprehensive and configurable model for modern enterprise Java applications
What is a cross-cutting concern? Examples of cross-cutting concerns?
The crosscutting 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.
What are the HTTP verbs?
The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively. There are a number of other verbs, too, but are utilized less frequently.
What are the different HTTP verbs/methods?
The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively. There are a number of other verbs, too, but are utilized less frequently.
What is REST? What are the constraints of REST?
The word REST applies to the transference of the Representation State. It is an architectonic style that specifies a collection of rules for web service development. Six Constraints: Client-Server, The uniform interface separates clients from servers. This separation of concerns means that, for example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved. Servers are not concerned with the user interface or user state so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface is not altered. Stateless, One client can send multiple requests to the server; however, each of them must be independent, that is, every request must contain all the necessary information so that the server can understand it and process it accordingly. In this case, the server must not hold any information about the client state. Any information status must stay on the client - such as sessions. Cacheable, Because many clients access the same server, and often requesting the same resources, it is necessary that these responses might be cached, avoiding unnecessary processing and significantly increasing performance. Uniform Interface, The uniform interface constraint defines the interface between clients and servers. It simplifies and decouples the architecture, which enables each part to evolve independently. This means: -HTTP Verbs (GET,POST,PUT,DELETE) -URIs (resource name) -HTTP response (status and body) Layered System, A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches. Layers may also enforce security policies. Code-On-Demand This condition allows the customer to run some code on demand, that is, extend part of server logic to the client, either through an applet or scripts. Thus, different customers may behave in specific ways even using exactly the same services provided by the server. As this item is not part of the architecture itself, it is considered optional. It can be used when performing some of the client-side services which are more efficient or faster.
What is a web service?
Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can include programs, objects, messages, or documents.
What is the difference between a framework and a library?
When you use a framework, the framework is in charge of the flow. It provides some places for you to plug in your code, but it calls the code you plugged in as needed. When you use a library, you are in charge of the flow of the application. You are choosing when and where to call the library.
What are some of the different ways in which we can wire beans? How do they work? What are the advantages/disadvantages of the different approaches?
You can manually wire beans with XML configuration, but this is laborious. Usually we use the @Autowired annotation, which can be used with properties, setters, and constructors. On properties (field injection), a bean is injected directly into a property, eliminating the need for getters and setters. On setters, a bean is injected when the setter method is called. On constructors, a bean is injected upon instantiation of the object.