spring
spring
@Component
public class Customer
{
private Person person;
@Autowired
public Customer(Person person){
this.person=person;
}
}
@Configuration
public class Vehicle
{
@Bean
Vehicle engine() {
return new Vehicle();
}
}
03. @Qualifier It can be used to create more than one bean of the same type and
wire only one of the types with a property. It provides greater control on the
dependency injection process and can be used with @Autowired annotation.
04. @Required Used to mark class members that are mandatory. The Spring auto-
configuration fails if a particular property specified with this annotation cannot
be injected.
@Required: It applies to the bean setter method. It indicates that the annotated
bean must be populated at configuration time with the required property, else it
throws an exception BeanInitilizationException.
public class Machine
{
private Integer cost;
@Required
public void setCost(Integer cost) {
this.cost = cost;
}
05. @ComponentScan Make Spring scan the package for the @Configuration clases.
@ComponentScan(basePackages = "com.javatpoint")
@Configuration
public class ScanComponent
{
// ...
}
07. @Bean It indicates that a method produces a bean which will be mananged by
the Spring container.
08. @Lazy Makes a @Bean or @Component to be initialized only if it is requested.
09. @Value It is used to inject values into a bean’s attribute from a
property file. @Value annotation indicates a default value expression for the field
or parameter.
10. @Resource Annotation used to inject an object that is already in the Appl-
ication Context. It searches the instance by name. It also works on setter methods.
11. @Primary Annotation used when no name is provided telling Spring to inject
an object of the annotated class first. Used along with @Component.
12. @Component Generic stereotype annotation used to tell Spring to create an
instance of the object in the Application Context. It’s possible to define any name
for the instance, the default is the class name as camel case.
@Component
public class Student
{
.......
}
13. @Controller Stereotype annotation for presentation layer.
@Controller
@RequestMapping("books")
public class BooksController
{
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public Employee getBooksByName()
{
return booksTemplate;
}
}
14. @Repository Stereotype annotation for persistence layer.
@Repository: It is a class-level annotation. The repository is a DAOs (Data Access
Object) that access the database directly. The repository does all the operations
related to the database.
package com.javatpoint;
@Repository
public class TestRepository
{
public void delete()
{
//persistence code
}
}
package com.javatpoint;
@Service
public class TestService
{
public void service1()
{
//business code
}
}
@Controller
public class BooksController
{
@RequestMapping("/computer-science/books")
public String getAllBooks(Model model)
{
//application code
return "bookList";
}
@GetMapping: It maps the HTTP GET requests on the specific handler method. It is
used to create a web service endpoint that fetches It is used instead of using:
@RequestMapping(method = RequestMethod.GET)
@PostMapping: It maps the HTTP POST requests on the specific handler method. It is
used to create a web service endpoint that creates It is used instead of using:
@RequestMapping(method = RequestMethod.POST)
@PutMapping: It maps the HTTP PUT requests on the specific handler method. It is
used to create a web service endpoint that creates or updates It is used instead of
using:
@RequestMapping(method = RequestMethod.PUT)
@DeleteMapping: It maps the HTTP DELETE requests on the specific handler method. It
is used to create a web service endpoint that deletes a resource. It is used
instead of using:
@RequestMapping(method = RequestMethod.DELETE)
@PatchMapping: It maps the HTTP PATCH requests on the specific handler method. It
is used instead of using:
@RequestMapping(method = RequestMethod.PATCH)
@RequestBody: It is used to bind HTTP request with an object in a method parameter.
Internally it uses HTTP MessageConverters to convert the body of the request. When
we annotate a method parameter with
@RequestBody, the Spring framework binds the incoming HTTP request body to that
parameter.
@ResponseBody: It binds the method return value to the response body. It tells the
Spring Boot Framework to serialize a return an object into JSON and XML format.
@PathVariable: It is used to extract the values from the URI. It is most suitable
for the RESTful web service, where the URL contains a path variable. We can define
multiple @PathVariable in a method.
@RequestParam: It is used to extract the query parameters form the URL. It is also
known as a query parameter. It is most suitable for web applications. It can
specify default values if the query parameter is not present in the URL.
@RequestHeader: It is used to get the details about the HTTP request headers. We
use this annotation as a method parameter. The optional elements of the annotation
are name, required, value, defaultValue. For each detail in the header, we should
specify separate annotations. We can use it multiple time in a method
@RestController: It can be considered as a combination of @Controller and
@ResponseBody annotations. The @RestController annotation is itself annotated with
the @ResponseBody annotation. It eliminates the need for annotating each method
with @ResponseBody.
@RequestAttribute: It binds a method parameter to request attribute. It provides
convenient access to the request attributes from a controller method. With the help
of @RequestAttribute annotation, we can access objects that are populated on the
server-side.
Aspect Annotations
Sl.No Annotation USE Description
01. @Aspect Type Declares a class to be an aspect.
02. @After Method Declares a method to be called after a pointcut
completes.
03. @AfterReturning Method Declares a method to be called after a pointcut
returns successfully.
04. @AfterThrowing Method Declares a method to be called after a pointcut
throws an exception.
05. @Around Method Declares a method that will wrap the pointcut.
06. @Before Method Declares a method to be called before proceeding to
the pointcut.
07. @DeclareParents Static Field Declares that matching types should be
given new parents,that is, it introduces new functionality into matching types.
08. @Pointcut Method Declares an empty method as a pointcut placeholder
method.
@SpringBootApplication
This application is the combination of so many different annotations which
includes:
@Configuration
@ComponentScan
@EnableAutoConfiguration
This annotation is used in the main class of our application it is the entry point
of our application as well.
Example:
@SpringBootApplication
class SpringBootDemo {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemo.class, args);
}
}
@EnableAutoConfiguration
This annotation is used to enable auto-configuration in our application. If a class
contains this annotation then spring boot automatically looks for all beans on the
classpath and automatically configures them.
Can you tell how to exclude any package without using the basePackages filter?
We can use the exclude attribute while using the annotation @SpringBootApplication
as follows:
@SpringBootApplication(exclude= {Student.class})
public class InterviewBitAppConfiguration {}
24. How to disable specific auto-configuration class?
You can use the exclude attribute of @EnableAutoConfiguration for this purpose as
shown below:
@EnableAutoConfiguration(exclude = {InterviewBitAutoConfiguration.class})
If the class is not specified on the classpath, we can specify the fully qualified
name as the value for the excludeName.
Auto-Configuration Conditions
We have different conditions for auto configurations. So when we write our own or
we can say custom configuration but we want spring to use them on some condition so
in order to achieve this we can use this condition annotation.
@Configuration
@ConditionalOnClass(DataSource.class)
class SqlConnectionDemo {
//...
}
@Bean
@ConditionalOnBean(name = "dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// ...
}
@Bean
@ConditionalOnProperty(
name = "username",
havingValue = "some-value"
)
DataSource dataSource() {
// ...
}
@ConditionalOnResource(resources = "classpath:mysql.properties")
Properties additionalProperties() {
// ...
}
@Bean
@ConditionalOnExpression("${usemysql} && ${mysqlserver == 'local'}")
DataSource dataSource() {
// ...
}
@Conditional: If you want to create some more and more complex conditions then we
can create a class which will turn to evaluate the custom condition.
Example:
@Conditional(HibernateCondition.class)
Properties additionalProperties() {
//...
The @RequestParam annotation can be used with or without a value. The value
specifies the request param that needs to be mapped to the handler method
parameter, as shown in this code snippet.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/id")
String getIdByValue(@RequestParam("id") String personId){
System.out.println("ID is "+personId);
return "Get ID from query string of URL with value element";
}
@RequestMapping(value = "/personId")
String getId(@RequestParam String personId){
System.out.println("ID is "+personId);
return "Get ID from query string of URL without value element";
}
}
In Line 6 of this code, the request param id will be mapped to the personId
parameter personId of the getIdByValue() handler method.
/home/name?person=xyz
/home/name
The default value of the @RequestParam is used to provide a default value when the
request param is not provided or is empty.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/name")
String getName(@RequestParam(value = "person", defaultValue = "John") String
personName ){
return "Required element of request param";
}
}
In this code, if the person request param is empty in a request, the getName()
handler method will receive the default value John as its parameter.
In order to define a request mapping with a specific HTTP method, you need to
declare the HTTP method in @RequestMapping using the method element as follows.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(method = RequestMethod.GET)
String get(){
return "Hello from get";
}
@RequestMapping(method = RequestMethod.DELETE)
String delete(){
return "Hello from delete";
}
@RequestMapping(method = RequestMethod.POST)
String post(){
return "Hello from post";
}
@RequestMapping(method = RequestMethod.PUT)
String put(){
return "Hello from put";
}
@RequestMapping(method = RequestMethod.PATCH)
String patch(){
return "Hello from patch";
}
}
In the code snippet above, the method element of the @RequestMapping annotations
indicates the HTTP method type of the HTTP request.
All the handler methods will handle requests coming to the same URL ( /home), but
will depend on the HTTP method being used.
For example, a POST request to /home will be handled by the post() method. While a
DELETE request to /home will be handled by the delete() method.
You can see how Spring MVC will map the other methods using this same logic.
In order to produce the object in the requested media type, you use the produces
element of @RequestMapping in combination with the @ResponseBody annotation.
You can also consume the object with the requested media type using the consumes
element of @RequestMapping in combination with the @RequestBody annotation.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/prod", produces = {"application/JSON"})
@ResponseBody
String getProduces(){
return "Produces attribute";
}
@RequestMapping(value = "/cons", consumes = {"application/JSON",
"application/XML"})
String getConsumes(){
return "Consumes attribute";
}
}
In this code, the getProduces() handler method produces a JSON response. The
getConsumes() handler method consumes JSON as well as XML present in requests.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/head", headers = {"content-type=text/plain"})
String post(){
return "Mapping applied along with headers";
}
}
In the above code snippet, the headers attribute of the @RequestMapping annotation
narrows down the mapping to the post() method. With this, the post() method will
handle requests to /home/head whose content-type header specifies plain text as the
value.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/head", headers = {"content-type=text/plain", "content-
type=text/html"}) String post(){
return "Mapping applied along with headers";
}
}
Here it implies that both text/plain as well as text/html are accepted by the
post() handler method.
You can define params as myParams = myValue. You can also use the negation operator
to specify that a particular parameter value is not supported in the request.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/fetch", params = {"personId=10"})
String getParams(@RequestParam("personId") String id){
return "Fetched parameter using params attribute = "+id;
}
@RequestMapping(value = "/fetch", params = {"personId=20"})
String getParamsDifferent(@RequestParam("personId") String id){
return "Fetched parameter using params attribute = "+id;
}
}
In this code snippet, both the getParams() and getParamsDifferent() methods will
handle requests coming to the same URL ( /home/fetch) but will execute depending on
the params element.
For example, when the URL is /home/fetch?id=10 the getParams() handler method will
be executed with the id value 10.. For the URL, localhost:8080/home/fetch?
personId=20, the getParamsDifferent() handler method gets executed with the id
value 20.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/fetch/{id}", method = RequestMethod.GET)
String getDynamicUriValue(@PathVariable String id){
System.out.println("ID is "+id);
return "Dynamic URI parameter fetched";
}
@RequestMapping(value = "/fetch/{id:[a-z]+}/{name}", method = RequestMethod.GET)
String getDynamicUriValueRegex(@PathVariable("name") String name){
System.out.println("Name is "+name);
return "Dynamic URI parameter fetched using regex";
}
}
In this code, the method getDynamicUriValue() will execute for a request to
localhost:8080/home/fetch/10. Also, the id parameter of the getDynamicUriValue()
handler method will be populated with the value 10 dynamically.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping()
String default(){
return "This is a default method for the class";
}
}
In this code, A request to /home will be handled by the default() method as the
annotation does not specify any value.
@RequestMapping Shortcuts
Spring 4.3 introduced method-level variants, also known as composed annotations of
@RequestMapping. The composed annotations better express the semantics of the
annotated methods. They act as wrapper to @RequestMapping and have become the
standard ways of defining the endpoints.
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
The following code shows using the composed annotations.
@RestController
@RequestMapping("/home")
public class IndexController {
@GetMapping("/person")
public @ResponseBody ResponseEntity<String> getPerson() {
return new ResponseEntity<String>("Response from GET", HttpStatus.OK);
}
@GetMapping("/person/{id}")
public @ResponseBody ResponseEntity<String> getPersonById(@PathVariable String
id){
return new ResponseEntity<String>("Response from GET with id "
+id,HttpStatus.OK); }
@PostMapping("/person")
public @ResponseBody ResponseEntity<String> postPerson() {
return new ResponseEntity<String>("Response from POST method", HttpStatus.OK);
}
@PutMapping("/person")
public @ResponseBody ResponseEntity<String> putPerson() {
return new ResponseEntity<String>("Response from PUT method", HttpStatus.OK);
}
@DeleteMapping("/person")
public @ResponseBody ResponseEntity<String> deletePerson() {
return new ResponseEntity<String>("Response from DELETE method",
HttpStatus.OK);
}
@PatchMapping("/person")
public @ResponseBody ResponseEntity<String> patchPerson() {
return new ResponseEntity<String>("Response from PATCH method", HttpStatus.OK);
}
}
In this code, each of the handler methods are annotated with the composed variants
of @RequestMapping. Although, each variant can be interchangeably used with
@RequestMapping with the method attribute, it’s considered a best practice to use
the composed variant. Primarily because the composed annotations reduce the
configuration metadata on the application side and the code is more readable.
ResponseEntity
ResponseEntity represents the whole HTTP response: status code, headers, and body.
As a result, we can use it to fully configure the HTTP response.
If we want to use it, we have to return it from the endpoint; Spring takes care of
the rest.
ResponseEntity is a generic type. Consequently, we can use any type as the response
body:
Since we specify the response status programmatically, we can return with different
status codes for different scenarios:
@GetMapping("/age")
ResponseEntity<String> age(
@RequestParam("yearOfBirth") int yearOfBirth) {
if (isInFuture(yearOfBirth)) {
return new ResponseEntity<>(
"Year of birth cannot be in the future",
HttpStatus.BAD_REQUEST);
}
@RestController
@RequestMapping(value = "/webapi")
public class EmployeeResource {
@Autowired
private EmployeeRepo employeeRepo;
return employeeRepo.findAll();
}
if (employeeRepo.findById(employeeId).isEmpty()) {
return
ResponseEntity.status(HttpStatus.NO_CONTENT).body(employee);
} else {
return ResponseEntity.status(HttpStatus.OK).body(employee);
employeeRepo.deleteById(employeeId);
return "Record Deleted : " + employeeId;
return
ResponseEntity.status(HttpStatus.NOT_FOUND).body(employee);
}
JPA
package com.example.accessingdatajpa;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
protected Customer() {}
@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
import java.util.List;
import org.springframework.data.repository.CrudRepository;
package com.example.accessingdatarest;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
package com.example.accessingdatarest;
import java.util.List;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
Can we change the default port of the embedded Tomcat server in Spring boot?
Yes, we can change it by using the application properties file by adding a property
of server.port and assigning it to any port you wish to.
For example, if you want the port to be 8081, then you have to mention
server.port=8081. Once the port number is mentioned, the application properties
file will be automatically loaded by Spring Boot and the specified configurations
will be applied to the application.
Before:
This advice executes before a join point, but it does not have the ability to
prevent execution flow from proceeding to the join point (unless it throws an
exception).
To use this, use @Before annotation.
AfterReturning:
This advice is to be executed after a join point completes normally i.e if a method
returns without throwing an exception.
To use this, use @AfterReturning annotation.
AfterThrowing:
This advice is to be executed if a method exits by throwing an exception.
To use this, use @AfterThrowing annotation.
After:
This advice is to be executed regardless of the means by which a join point exits
(normal return or exception encounter).
To use this, use @After annotation.
Around:
This is the most powerful advice surrounds a join point such as a method
invocation.
To use this, use @Around annotation
BeanFactory
ApplicationContext
Question: What is the basic difference between Mono and Flux in Spring?
Answer: Mono implements the publisher and returns 0 or even one element while the
Flux implements the publisher and return N elements.
Answer: There are many standard Spring events serving respective purpose and few
among them are ContextStartedEvent, ContextRefreshedEvent, ContextStoppedEvent,
ContextClosedEvent, RequestHandledEvent etc.
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 as 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 the 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.
The first one is set up which is called when the bean is loaded into 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 corresponding annotations(@PostConstruct and @PreDestroy).
no: This is the default setting. An explicit bean reference should be used for
wiring.
byName: When auto-wiring byName, the Spring container looks at the properties of
the beans on which the auto-wire 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 auto-wire 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 names of the bean in the 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 auto-wire by the constructor, if it
does not work, Spring tries to auto-wire by type.