JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Spring Boot Configurations

March 25, 2016 by Krishna Srinivasan Leave a Comment

Spring Boot uses application.properties or application.yml for configuring the various application level settings. As we are aware that spring boot works with the opinionated default values that are more sensible to your applications. Most of the time you may prefer to override the default values with your own configurations.

In this tutorial I am going to explain about some of the important properties used for spring boot configurations that are frequently used in the spring boot application and you may wish to override those values.

Spring Boot Configurations
Spring Boot Configurations

Note: The application.properties is optional and spring boot could start running without this configuration file.

Spring Boot Configurations

Table of Contents:

  1. Properties File Location
  2. Application Configuration File Name
  3. Server Port Number
  4. Context Path
  5. Application Reload
  6. Enable H2 Web Console
  7. Enable Actuator EndPoints
  8. Log File Configurations
  9. Enable Favicon Image
  10. View Resolver Configuration

1. Properties File Location

Before start looking at the configuration properties, lets understand the location of properties file. You must keep your application.properties in any of the following locations.

Spring Boot Configuration File Locations:

  1. /config directory under the current directory.
  2. Current Directory
  3. /config under the classpath
  4. Root of the classpath

The search of the properties file start from the lower of the above list. If you have properties file in the multiple locations, then higher location in the above list will override the files found in the lower locations.

Any other locations other than the mentioned above will not be searched by spring boot to fetch the configuration files unless you explicitly modify the location of the properties file.

If you are looking for a more in-depth tutorial on spring boot configuration file, please read our tutorial that talks about External Configurations for Spring Boot.

2. Application Configuration File Name

By default spring boot searches for the file name application.properties or application.yml to load the application configurations. If you have only one spring boot application then there is no need to worry about changing the configuration properties file name. But, if you have more than one spring boot applications, then you may like to change the properties file name.

But, these names are decided at the very early stage of the spring boot startup, so we can not update the values directly in the application.properties or application.yml file. Instead, we have to pass the parameters spring.config.name and spring.config.location as an argument while starting the application.
Something like this:

[code]
$ java -jar springapp.jar –spring.config.name=myproject
[/code]

or

[code]
$ java -jar springapp.jar –spring.config.location=classpath:/my.properties,classpath:/override.properties
[/code]

3. Server Port Number

Most of the web servers, the default server port number is 8080. But, in some cases, you want to change the port number that is different from the default one. Please add the following lines to your application.properties :

[code]
server.port=7070
[/code]

If you are using YAML based configuration:

[code]
server:
port: 7070
[/code]

Programmatically customize the server port as follows:

[code lang=”java”]
@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(7070);
}
}
[/code]

4. Context Path

Spring Boot sets / as the default context root for the web applications if you are not configuring your own context root. If you are interested in updating the context path, please add the following lines in your application.properties file:

[code]
server.contextPath=/webapp
[/code]

If you are using yaml configuration:

[code]
server:
contextPath:/webapp
[/code]

For programmatic changes please add the following code:

[code lang=”java”]
@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setContextPath("/webapp");
}
}
[/code]

5. Application Reload

Since spring boot 1.3.0, any changes to classpath will trigger an application restart. This feature is introduced as part of the Spring Boot DevTools module. You can enable or disable this feature by adding the following lines to application.properties file:

[code]
spring.devtools.livereload.enabled=false
[/code]

If you are interested in learning more about live reload and spring boot devtools features, please read our comprehensive tutorial on spring boot devtools module.

6. Enable H2 Web Console

H2 database is an in-memory database that is frequently used at development phase of the application due to its simplicity and easy configurations. This database offers web console module for managing the database used by your applications. With the use of web console, a developer can view the tables and run the query to manipulate database at runtime.

By default, spring boot disables the web console. You can enable and modify the path where web console is accessible by adding the following lines in your application.properties:

[code]
spring.h2.console.enabled=false
spring.h2.console.path=/h2-console
[/code]

7. Enable Actuator EndPoints

One of the nice features in spring boot is actuator endpoints. This enables the metrics for your applications that are very useful for the production applications. By default, this is disabled by spring boot configurations. You can enable this feature by adding the following lines in your application.properties:

[code]
endpoints.enabled=true
[/code]

Once you have added the above entry into your configuration properties file, the default endpoints will be enabled and exposed as a REST Service that returns the JSON result back to the web browser.

Please read the more comprehensive tutorial on spring boot actuator endpoints that covers every important feature of spring boot actuator configurations.

8. Log File Configurations

It is very simple to configure the log file information. Some of the common logging configurations are log file location, log file name, configuration file, etc. Please add the following lines in your application properties file:

[code]
logging.config=# Location of the logging configuration file. For instance ‘classpath:logback.xml’ for Logback
logging.file= # Log file name. For instance ‘myapp.log’
logging.level.*= # Log levels severity mapping. For instance ‘logging.level.org.springframework=DEBUG’
logging.path= # Location of the log file. For instance ‘D:/log’
[/code]

Apart from the above key properties, many other properties are available to customize the logging configurations. By default, spring boot supports the LogBack logging mechanism. We have written a detailed tutorial on logging configurations in spring boot that is worth reading to get a good understanding on spring boot logging.

9. Enable Favicon Image

Favicon is the small icon that is displayed on top of the browser, generally that is will be the tiny logo of the application. Add the following properties entry in your Spring MVC application to enable the favicon:

[code]
spring.mvc.favicon.enabled=true
[/code]

10. View Resolver Configuration

When we are using the view resolver, we have to specify the prefix and suffix details to the InternalResourceViewResolver. That can be achieved by adding the following entries:

[code]
spring.mvc.view.prefix= /WEB-INF/JSP/
spring.mvc.view.suffix= .jsp
[/code]

The above properties files are used for working with the Spring MVC application.

Summary

In this tutorial, I have walked you through the some of the important spring boot properties configurations for enabling and disabling the features such as logging, actuator, favicon, spring MVC view resolver, dev tools features, h2 web console, etc. with brief explanation that helps you to get started with that specific features.

Apart from the above list, this tutorial explained the steps to change the config file name, locations and the order of the precedence on finding the config files at spring boot startup (Also Read: Spring Boot Startup Events).

If you are using spring boot in your application, I am happy to help you on resolving any issues you are encountering with spring boot projects. Please send me a mail at Krishnas at javabeat.net with your questions.

Thank you for reading my blog!! Happy Reading!!

Filed Under: Spring Framework Tagged With: Actuator EndPoints, Enable Favicon Image, H2 Web Console, Log File Configurations, Properties File Location, Spring Boot, Spring Boot Tutorials, Spring MVC application, View Resolver Configuration

Spring Data + MongoDB + REST Shell Integration

May 19, 2014 by Amr Mohammed Leave a Comment

This tutorial guides you through an example for understanding the integration between Spring Data, Spring REST and MongoDB. As you are going to use the rest-shell for achieving different operations against database. Entities will be persisted into MongoDB in the form of which an outer entity will save a reference to the inner one. Unlike the most of the examples that are published in previous tutorials here. Also, you’d see the integrating of Spring Boot for initializing of an embedded Apache Tomcat.

Also read:

  • Spring Roo + Spring Data JPA Repositories + Eclipse Integration
  • Spring Data JPA + Querydsl
  • Spring Data + MongoDB 
  • Connect With Us : Google+ | Twitter | FaceBook

1. Tools Required

The required platforms and environments for this tutorial:

  • JDK 1.7.
  • Maven 3.2.1.
  • Eclipse IDE Kepler 4.3.
  • Spring Data
  • MongoDB

2. Java Beans (Entities)

Address and Employees entities will be used for defining the business domain.

Address.java

[code lang=”java”]
package net.javabeat.springdata.data;

import javax.persistence.Id;

import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Document(collection="Address")
public class Address {
@Id
@Field
private String id;
@Field
private String addressCountry = "";
@Field
private String addressCity = "";

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAddressCountry() {
return addressCountry;
}
public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}
public String getAddressCity() {
return addressCity;
}
public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

Employee.java

[code lang=”java”]
package net.javabeat.springdata.data;

import javax.persistence.Id;

import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Document(collection="Employee")
public class Employee {
@Id
@Field
private String id;
@Field
private String employeeName;
@DBRef
private Address address;

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
[/code]

3. Spring Data Repositories

It’s the spring data repositories that will be used for communicating with the MongoDB for any CRUD operation.

AddressRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Address;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel="address",path="address")
public interface AddressRepository extends CrudRepository<Address,String>{
}
[/code]

EmployeeRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Employee;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel="employee",path="employee")
public interface EmployeeRepository extends CrudRepository<Employee, String>{
}
[/code]

4. Spring Context Configuration

Here is the required spring context configuration for communicating to the MongoDB.

SpringContext.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

<!– Register Mongo Instance –>
<mongo:mongo id="mongo" host="localhost" port="27017" />
<!– for defining mongo template –>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="JavaBeat" />
</bean>

<!– For consider the using of annotations foe defining Spring Bean –>
<context:annotation-config />

<!– For defining Spring Bean –>
<context:component-scan base-package="net.javabeat.springdata.beans" />
<!– For defining mongo repository –>
<mongo:repositories base-package="net.javabeat.springdata.repo" />

</beans>
[/code]

5. Executable Application

This stand alone spring boot application will start this sample application.

Executable.java

[code lang=”java”]
package net.javabeat.springdata.executable;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;

@Configuration
@EnableMongoRepositories
@Import(RepositoryRestMvcConfiguration.class)
@ImportResource("classpath:SpringContext.xml")
@EnableAutoConfiguration
public class Executable {

public static void main(String[] args) {
SpringApplication.run(Executable.class, args);
}
}
[/code]

6. Maven Dependencies

It’s the maven libraries that define the required libraries for the suggested communication with the MongoDB through Spring REST.

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>net.javabeat.springdata</groupId>
<artifactId>SpringData-MongoDB-REST</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>Spring Data</name>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.2.RELEASE</version>
</parent>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

<dependencies>

<!– Dependency for Spring Boot –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-core</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
</dependencies>

</project>

[/code]

7. Install REST Shell

Rest shell is the native engine that provided by Spring and can be downloaded from here. After downloading the shell, you can unzip it into any location that you suggested.

Open the command line and navigate into the unzipped location that you already selected before and type into command line rest-shell and press enter. Be sure that your application is up and running before any further uses of the shell.

Rest-Shell Starting Up

8. MongoDB + Spring Data Repository + Spring REST Demo

Inside this demonstration, set of snapshots has been used for clarifying the operations of READ, PERSIST & DELETE operations.

List all of collections inside MongoDB

Follow address - getting the address of id 1

Follow employee - getting the employee of id 1

Create Employee and Associate it with the already created Address entity

List of Addresses

List all employees

9. MongoDB Collections

Database address records

Database employee records

10. Accessing Through HTTP

HTTP employees list

11. Summary

Congratulations, you’ve just developed an application that uses the Spring REST for getting successful operations against MongoDB.

Download Source Code

[wpdm_file id=100]

Filed Under: Spring Framework Tagged With: MongoDB, Spring Boot, Spring Data, Spring REST

Spring Data Neo4j 3 REST Exporter – Converting Spring Boot JAR Application To WAR

May 16, 2014 by Amr Mohammed Leave a Comment

This tutorial is the continuation of the previous tutorial for building the standalone application using spring boot. This guide walks you through the process of converting a runnable JAR application that was built with Spring Boot into a WAR file that you can run in any standard servlet container. You’ll take a simple Spring MVC web app and build a WAR file using Spring Boot.

Also read:

  • Spring Roo + Spring Data JPA Repositories + Eclipse Integration
  • Spring Data JPA + Querydsl
  • Spring Data + MongoDB 
  • Connect With Us : Google+ | Twitter | FaceBook

1. Java Beans

It’s the entities that will be used for representing the persisted nodes.

Address.java

[code lang=”java”]
package net.javabeat.springdata.data;

import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;

@NodeEntity
public class Address{

@GraphId
private Long id;

private String addressCountry;

private String addressCity;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getAddressCountry() {
return addressCountry;
}

public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}

public String getAddressCity() {
return addressCity;
}

public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

Employee.java

[code lang=”java”]
package net.javabeat.springdata.data;

import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;

@NodeEntity
public class Employee{
@GraphId
private Long id;

private String employeeName;

@Fetch
@RelatedTo(type="Address")
private Address address = new Address();

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}
}
[/code]

2. Spring Data Neo4j Repositories

It’s the repositories that will be used for operating against the graph database through different operations.

EmployeeRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Employee;

import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface EmployeeRepository extends GraphRepository<Employee>{

}
[/code]

AddressRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Address;

import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "address", path = "address")
public interface AddressRepository extends GraphRepository<Address>{

}

[/code]

3. Spring Controller

It’s Spring MVC controller that allows you to quickly build controllers for your web site. The controller is very simple, in that the @Controller annotation tells the container that this class contains web application paths. @RequestMapping annotation ensures that HTTP request to /query mapped to the query method and /execute mapped to the execute one.

DataController.java

[code lang=”java”]
package net.javabeat.springdata.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DataController {

@RequestMapping(value="/execute", method=RequestMethod.GET,params="query")
public String execute(@RequestParam ("query")String query,HttpServletRequest request, HttpServletResponse response) {
try {
response.getWriter().write("<h1>JavaBeat Tutorials</h1>");
response.getWriter().write("<h2>Neo4j + REST + Spring Boot WAR Application</h2>");
URL url = new URL("http", "localhost",8080,"/JavaBeat-Neo4j-REST/"+request.getParameter("query"));
HttpURLConnection c = (HttpURLConnection)url.openConnection();
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.connect();
int status = c.getResponseCode();

switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
response.getWriter().append(line+"\n");
}
br.close();
response.flushBuffer();
return "resultTemplate";
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "resultTemplate";
}

@RequestMapping(value="/query", method=RequestMethod.GET)
public String query(HttpServletRequest request, HttpServletResponse response) {
try {
response.getWriter().write("<h1>JavaBeat Tutorials</h1>");
response.getWriter().write("<h2>Neo4j + REST + Spring Boot WAR Application</h2>");
} catch (IOException e) {
e.printStackTrace();
}
return "queryTemplate";
}
}
[/code]

4. Thymeleaf Templates

Spring Boot automatically added Thymeleaf beans to the application context to convert a request for the Thymeleaf template located at

  • src/main/resource/templates/queryTemplate.html, which responsible for gathering the query from the user.
  • src/main/resource/templates/resultTemplate.html, which responsible for displaying the result of the queries.

Those templates has very basic HTML elements and no actual Thymeleaf code.

queryTemplate.html

[code lang=”xml”]
<html>
<body>
<form id="form" action="execute" method="GET">
<p>Enter Query You Want To Be Executed Right Below:</p>
<br />
<input id="query" name="query" type="text" value=""/>
<input type="submit" value="Query !"/>
</form>
</body>
</html>
[/code]

resultTemplate.html

[code lang=”xml”]
<!– It’s filled by using the controller response.getWriter() –>
[/code]

4. Executable Application

Already, you have made the application an executable JAR file in the first part of this tutorial. You package everything in a single, executable JAR driven by main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance. In this part of tutorial, you will see how to build WAR file to run it on a standard container.

Executable.java

[code lang=”java”]
package net.javabeat.springdata.executable;

import org.neo4j.graphdb.GraphDatabaseService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.rest.SpringRestGraphDatabase;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
@ComponentScan("net.javabeat")
@Configuration
@EnableNeo4jRepositories("net.javabeat.springdata.repo")
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Executable extends Neo4jConfiguration {

public Executable() {
}

@Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
SpringRestGraphDatabase service = new SpringRestGraphDatabase("http://localhost:7474/db/data/");
this.setBasePackage("net.javabeat");
return service;
}

public static void main(String[] args) {
SpringApplication.run(Executable.class, args);
}
}
[/code]

5. Run the Service

If you’ve ran the service by using the java -jar or by using the Eclipse IDE running Java application, you will be able to display the templates contents using a resource identifier started with http://localhost:8080/query.

Execute Spring Boot Application Using JAVA

But even if you have provided the input shown a query like employee, you will not be able to see the result, cause the remaining functionality needs the remaining configuration for web application.

6. Build WAR File

The application you built up to this point is configured to generate a JAR artifcat. To switch it to WAR file, you need change the packaging attribute in the pom.xml into war. Also, if you want to deploy the WAR file into external container, you also need to mark the embedded container dependencies as provided.

7. Initialize the Servlet

Previously, the application contained a public static void main() method which consider a Spring Boot configuration was used when using the java -jar command. By converting this into WAR file with no XML files, you need a different message to the servlet container on how to launch the application. So that you have to provide your own WebXML Java class.

WebXML.java

[code lang=”java”]
package net.javabeat.springdata.webXML;

import net.javabeat.springdata.executable.Executable;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

public class WepXML extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Executable.class);
}
}
[/code]

WebXML is a pure Java class that provides an alternative to creating a web.xml. It extends the SpringServletInitializer class. This extension offers many configurable options by overriding methods. But one required method is configure().

Configure() provides the means to register the classes that are needed to launch the application. This is where you supply a handle to your Executable configuration. Even though public static void main() is no longer needed, you can leave that code in place.

8. Run the WAR file

It’s the demonstration that we would provide you for making everything clear for you. Just build your application and make sure maven has created your WAR. Put your WAR into the tomcat 8 webapp folder and starting the tomcat up. Another way you would follow by integrating your Eclipse IDE with your Tomcat 8 and Right Click on the project folder and use Run As.

Neo4j REST WAR Running Default Location Neo4j REST WAR Running Query Page Neo4j REST WAR Running Execute Page

Neo4j REST WAR Running Query Page Address Neo4j REST WAR Running Execute Page Address

Download Source Code

[wpdm_package id=’23180′]

Filed Under: Spring Framework Tagged With: Neo4j, Spring Boot, Spring Data, Spring REST, WAR

Spring Data Neo4j 3 REST Exporter (Java Application)

May 16, 2014 by Amr Mohammed Leave a Comment

This tutorial walks you through the process of creating an application that accesses graph-based data through a hypermedia-based RESTful front end. You’ll build a Spring application that let’s you create and retrieve Employee and Address objects stored in a Neo4j NoSQL database (Neo4j Server) using Spring Data REST. You’ll use the non embedded Neo4j for achieving the exporter, and the Tomcat 8 for running the Spring Boot application.

Also read:

  • Spring Roo + Spring Data JPA Repositories + Eclipse Integration
  • Spring Data JPA + Querydsl
  • Spring Data + MongoDB 
  • Connect With Us : Google+ | Twitter | FaceBook

1. Install Eclipse Tomcat 8 Plugin

You have to install and use the Tomcat 8 and JDK 1.7 to run the example application used in this tutorial. Eclipse IDE provides you the Tomcat 8 plugin that can be downloaded from here. Tomcat 8 support is not added to the Eclipse at the time of writing this tutorial. So, download the eclipse from the given link and use it.

After downloading the plugin you have to follow the below steps for completing the plugin installation:

  • Copy the downloaded file beside your root eclipse folder. Let you have an installed eclipse at D:\eclipse, the zip file should be beside the eclipse not within it.
  • Extract the zip file using extract here.
  • Restart the eclipse ide.
  • Install Tomcat 8 from here.
  • Extract your downloaded Tomcat at your preferred folder.
  • Add a new server using the new server wizard and make sure you have selected the Tomcat 8.
  • While you are installing the Tomcat 8 through wizard, you will be enforced to use a JDK .17 for completing the installation.

Tomcat 8 will not be shown in this tutorial, but it will be important in the next part when a Spring Boot pure Java Application converted into WAR. But the minimum requirement for running the Tomcat 8 is Java 7.

2. Java Beans

It’s the beans (Address and Employees) that will be used for REST exporting process, by which all of the persisted entities inside the Neo4j database have exposed using HTTP.

Address.java

[code lang=”java”]
package net.javabeat.springdata.data;

import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;

@NodeEntity
public class Address{

@GraphId
private Long id;

private String addressCountry;

private String addressCity;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getAddressCountry() {
return addressCountry;
}

public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}

public String getAddressCity() {
return addressCity;
}

public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

Employee.java

[code lang=”java”]
package net.javabeat.springdata.data;

import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;

@NodeEntity
public class Employee{
@GraphId
private Long id;

private String employeeName;

@Fetch
@RelatedTo(type="Address")
private Address address = new Address();

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}
}
[/code]

3. Spring Data Repositories

Create the spring data repositories for the each persistence type and leave the actual implementation to the spring data run time.

EmployeeRepositories.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Employee;

import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface EmployeeRepository extends GraphRepository<Employee>{}
[/code]

AddressRepositories.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.data.Address;

import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "address", path = "address")
public interface AddressRepository extends GraphRepository<Address>{}
[/code]

4. Executable Application

It’s the main application that uses the Spring Boot concept to execute the Spring Application. It contains the all configuration required for setting up the context as all of those required information such as the GraphDatabaseService, base package and the repositories package. Executable main class got executed using the normal execution for any Java Class which contains a main method. Spring Boot will use the Embedded Tomcat

Executable.java

[code lang=”java”]
package net.javabeat.springdata.executable;

import org.neo4j.graphdb.GraphDatabaseService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.rest.SpringRestGraphDatabase;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;

@Configuration
@EnableNeo4jRepositories("net.javabeat.springdata.repo")
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Executable extends Neo4jConfiguration {

public Executable() {
}

@Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
SpringRestGraphDatabase service = new SpringRestGraphDatabase("http://localhost:7474/db/data/");
this.setBasePackage("net.javabeat");
return service;
}

public static void main(String[] args) {
SpringApplication.run(Executable.class, args);
}
}
[/code]

5. Maven Dependencies

This pom.xml maven file defines all the dependencies used in this tutorial.

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>next.javabeat.jsf</groupId>
<artifactId>JavaBeat-Neo4j-REST</artifactId>
<packaging>jar</packaging>
<version>1.0</version>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.2.RELEASE</version>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j-rest</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
</dependencies>

<properties>
<!– use UTF-8 for everything –>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<start-class>net.javabeat.springdata.executable.Executable</start-class>
</properties>

<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

<repositories>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>

</project>
[/code]

6. Neo4j REST Demo

It’s just a demonstration for the form of the JSON response, once an HTTP request has been sent from the browser. For exposing the JSON reponse, we used the Google HTTP DEV plugin.

Neo4j REST

Neo4j-REST-ADDRESS

Neo4j-REST-EMPLOYEE

Download Source Code

[wpdm_package id=’23182′]

Filed Under: Spring Framework Tagged With: Neo4j, Spring Boot, Spring Data, Spring REST

Spring Data REST Exporter

May 8, 2014 by Amr Mohammed Leave a Comment

This tutorial provides the detailed instruction on how to use Spring Data REST project in your Spring MVC applications to export your JPA entities. The greatest advantage of using the Spring Data REST is that, it easily exports the entities and made available through the HTTP protocol.

Using Spring Data REST repository exporter project, you can now export these managed entities via a REST web service to easily interact with the data. The exporter mechanism will transparently expose a resource per repository, map CRUD operations onto HTTP methods for that resource, and provide facility to execute the query methods exposed on the repository interface.

But before getting started with Spring Data Exporter , it is important to have a understanding on the REST concept. Also, it is worthy to know that this tutorial will try to simplify the concept of REST by considering the Spring Boot for implementing a standalone spring mvc application.

1. REST

REST stands for Representational State Transfer (REST) is an architectural style. It is a generalization of the principles behind the HTTP protocol, from which it derives the following core concepts:

  • Resources: Systems expose resources to other systems: an Employee, an Address, and so on.
  • Identifiers: These resources can be addressed through an identifier. In the HTTP world, these identifiers are URIs
  • Verbs: Each resource can be accessed and manipulated though a well-defined set of verbs. The most common verbs used in the HTTP are GET, POST, DELETE, HEAD and OPTIONS.
  • Representations: A client never interacts with the resource directly but rather through representations of it. As you will be seeing inside this tutorial, the JSON should be used for representing the resources.

2. Persistence Entities

We are using the Employee and Address persistence entity for this tutorials. Lets look at the implementation of these entities and how it is modeled in the database schema. Note that this example uses Java Persistence API (JPA) for the entity exporter. We can use any other persistence provider supported by Spring Data Rest for exporting the entities. Only change will be the persistence repository.

Employee.java

[code lang=”java”]
package net.javabeat.springdata.jpa.data;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Employee {

@Id
private Integer employeeId;

@Basic(optional = false)
private String employeeName;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Address")
private Address address;

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public Integer getEmployeeId() {
return employeeId;
}

public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public boolean equals(Object obj){
if(obj instanceof Employee){
Employee emp = (Employee)obj;
if(this.employeeId == emp.employeeId){
return true;
}
}
return false;
}

public int hashCode(){
return this.employeeId;
}

}
[/code]

Address.java

[code lang=”java”]
package net.javabeat.springdata.jpa.data;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity(name = "address")
public class Address {
@Id
private Integer addressId;
private String addressCountry;
private String addressCity;

@OneToOne(cascade = CascadeType.ALL, mappedBy = "address")
private Employee employee;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public int getAddressId() {
return addressId;
}

public void setAddressId(int addressId) {
this.addressId = addressId;
}

public String getAddressCountry() {
return addressCountry;
}

public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}

public String getAddressCity() {
return addressCity;
}

public void setAddressCity(String addressCity) {
this.addressCity = addressCity;
}
}
[/code]

For your convenience, we have provided the database schema design which will help you for writing the example. Also you can download the example source code at the bottom of this tutorial.

Employee Table

Employee Foreign Key

Address Table

3. JPA Context Configurations

Here is the persistence context used for this tutorial. This configuration file provides configuration details for the MYSQL database driver and the above mentioned persistence entities.

persistence.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="SpringData" transaction-type="RESOURCE_LOCAL">
<class>net.javabeat.springdata.jpa.data.Employee</class>
<class>net.javabeat.springdata.jpa.data.Address</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/JavaBeat" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="eclipselink.logging.level" value="OFF" />
</properties>
</persistence-unit>
</persistence>
[/code]

4. Spring Application Context Configurations

Here is the spring context configuration for this example. For more details about the configurations, please read Spring Data – JPA tutorial.

SpringContext.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

<!– For consider the using of annotations foe defining Spring Bean –>
<context:annotation-config />

<!– For defining Spring Bean –>
<context:component-scan base-package="net.javabeat.springdata.beans" />

<!– For bootstrapping the Spring Repository –>
<jpa:repositories base-package="net.javabeat.springdata.repo" />

<!– Necessary to get the entity manager injected into the factory bean –>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<!– Define EclipseLink JPA Vendor Adapter –>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
<property name="generateDdl" value="false" />
<property name="showSql" value="true" />
</bean>

<!– Entity Manager Factory –>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="SpringData"></property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>

<!– Transaction Manager –>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<!– Enable Transactional Manner –>
<tx:annotation-driven transaction-manager="transactionManager" />

</beans>
[/code]

5. Spring REST Repositories

For exposing your repositories as a REST, you have to define the repositories using the @RepositoryRestResource annotation.

EmployeeRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Employee;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface EmployeeRepository extends CrudRepository<Employee, Integer>{}
[/code]

AddressRepository.java

[code lang=”java”]
package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.Address;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "address", path = "address")
public interface AddressRepository extends CrudRepository<Address,Integer>{}
[/code]

6. Maven Dependencies For Spring Data Rest

pom.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.javabeat.springdata</groupId>
<artifactId>SpringData-JPA</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Spring Data</name>
<!– Inherit defaults from Spring Boot –>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.2.RELEASE</version>
</parent>
<dependencies>
<!– Dependencies for Eclipse JPA Persistence API –>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0-RC1</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
<!– Dependency for MySql Java connector –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!– Spring Data Dependency –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<!– Dependency for REST Exporter –>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
<!– Required Spring Boot Web Application Dependency –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!– Required Spring Boot JPA Dependency –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
</project>
[/code]

7. Spring Data REST Exporter Example Application

This example application is executed using the Spring Boot application. If you have the Tomcat runtime in your machine, this below example will embed the tomcat and spring mvc application.

Executable.java

[code lang=”java”]
package net.javabeat.springdata.executable;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;

@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@ImportResource("classpath:SpringContext.xml")
@EnableAutoConfiguration
public class Executable {

public static void main(String[] args) {
SpringApplication.run(Executable.class, args);
}
}
[/code]

8. Running Application

You can now access the Spring Data Rest through browser which will be exposed as the REST services.

Address Repository

Access Spring Repositories

Employee Repository

9. Summary

Spring Data provides the Spring Developer that ability to create a REST web services against already user defined CRUD repositories. This service is limited to the CRUD repositories but in the next coming releases other types of repositories should be supported.

Download Source Code

  • Download Source Code

Filed Under: Spring Framework Tagged With: Spring Boot, Spring Data, Spring REST

Spring Boot 1.0.0.RC5 Released!!

March 22, 2014 by Krishna Srinivasan Leave a Comment

This week Spring IO team has announced that they have released the final released candidate for the Spring Boot 1.0.0 road map. So, the next version will be the final release of the project. Spring Boot project is intended to use the auto configuration of your spring applications instead of developers manually configure the environmental requirements. With this release, there are few new features added to the 1.0.0 release. (Read : Introduction to Spring Boot)

spring-boot-diagram

Spring Boot 1.0.0.RC5 New Features

  • A new @IntegrationTest annotation has been added to help when writing integration tests for Spring Boot.
  • The CRaSH shell now exposes an endpoint command that can be used to obtain actuator information.

The reference material for this project is updated and have lot of information for the developers to get started on writing their Spring Book  applications.

Filed Under: Spring Framework Tagged With: Releases, Spring Boot

Difference Between @Resource, @Autowired and @Inject in Spring Injection

October 26, 2013 by Krishna Srinivasan Leave a Comment

Build Your REST API with Spring - VIDEO Courses

It is very common confusion among the spring developers that what is the real difference between these three (@Resource, @Autowired and @Inject) annotations used for injecting the objects. I have come across this question from our readers so dedicated this post for explaining the main difference between these three annotations. Infact, these three work very much similar in most of the cases, there is slight differnce in few cases. I would explain that in this post. lets start from the basic details about these three annotations.

  1. @Resource – Defined in the javax.annotation package and part of Java
  2. @Inject – Defined in the javax.inject package and part of Java
  3. @Autowired – Defined in the package org.springframework.bean.factory and part of Spring framework.

Here I am creating a simple interface Car which has two implementation classes Volkswagen and Toyota. We are going to inject these three types to understand the difference between these annotations. Lets look at the class below. These are only the code snippets, if you want to run this example please have a complete setup of your spring application.

Also read:

  • Spring MVC Framework with Example
  • Spring Framework Interview Questions
  • Spring Aspect Oriented Programming (AOP)

Car.java

[code lang=”java”]
package javabeat.net.basic;
public interface Car {
}
[/code]

Volkswagen.java

[code lang=”java”]
package javabeat.net.basic;
import org.springframework.stereotype.Component;
@Component
public class Volkswagen implements Car{}
[/code]

Toyota.java

[code lang=”java”]
package javabeat.net.basic;
import org.springframework.stereotype.Component;
@Component
public class Toyota implements Car{}
[/code]

Inject Interface

[code lang=”java”]
@Resource
private Car car;

@Autowired
private Car car;

@Inject
private Car car;
[/code]

The following exception is thrown when executing the all the above code:

[code]
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [javabeat.net.basics.Car] is defined:
expected single matching bean but found 2: [volkswagen, toyota]
[/code]

Field Type

[code lang=”java”]
@Resource
private Volkswagen car;

@Autowired
private Volkswagen car;

@Inject
private Volkswagen car;
[/code]

The above code works fine for all the above definitions. All the three types inject the type of bean “Volkswagen” by using the bean type.

Qualifier name

[code lang=”java”]
@Resource
@Qualifier("volkswagen")
private Car car;

@Autowired
@Qualifier("volkswagen")
private Car car;

@Inject
@Qualifier("volkswagen")
private Car car;
[/code]

All the above three annotations inject Volkswagen bean by considering the @Qualifier annotation.

Conflicting Information

[code lang=”java”]
@Resource
@Qualifier("nkl")
private Car volkswagen;

@Autowired
@Qualifier("nkl")
private Car volkswagen;

@Inject
@Qualifier("nkl")
private Car volkswagen;
[/code]

In the above code, @Resource works fine and inject the Volkswagen type. But, @Autowired and @Injects throws the follwing exception.

[code lang=”java”]
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [javabeat.net.basics.Car] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true),
@org.springframework.beans.factory.annotation.Qualifier(value=nkl)}
[/code]

The main difference is that, @Autowired and @Inject works similar for 100% without any differentiation.These two annotations using AutowiredAnnotationBeanPostProcessor to inject dependencies. But,@Resource uses CommonAnnotationBeanPostProcessor to inject dependencies and there is difference in the order of checking.

@Autowired and @Inject

  1. Matches by Type
  2. Restricts by Qualifiers
  3. Matches by Name

@Resource

  1. Matches by Name
  2. Matches by Type
  3. Restricts by Qualifiers (ignored if match is found by name)

I hope this article would have provided good insight into these three annotations. If you have any questions, please write it in the comments section.

Filed Under: Spring Framework Tagged With: Spring Boot

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved