@Component @Controller @Service and @Repository annotations example using spring boot

In this post, we will see @Component @Controller @Service and @Repository annotations example using spring boot. First, we will see some basics about these annotations. Later we will have an example where we will see how to use these annotations.

 

Basic points about @Component @Controller @Service and @Repository annotations.

@Component annotation.

  • This annotation introduced in spring 2.5,  available in org.springframework.stereotype package.
  • This annotation used with classes and interfaces.
  • When we use this annotation with class, that class will be available for auto detection(automatically bean will be created) while using component scan based annotation configuration.
  • internal implementation.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {

}

 

 

@Service annotation.

  • This annotation introduced in spring 2.5,  available in org.springframework.stereotype package.
  • This annotation used with classes and interfaces.
  • This annotation behaves similarly to @Component. The only difference it helps our classes more readable, using this annotation with class indicates this is our service class(mostly our business logic exist in these classes).
  • internal implementation.
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

}

 

@Repository annotation – 

  • This annotation introduced in spring 2.0,  available in org.springframework.stereotype package.
  • This annotation used with DAO interfaces.
  • internal implementation.
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {

}

 

@Controller annotation.

  • This annotation introduced in Spring 2.5, available in org.springframework.stereotype package.
  • We use this annotation with the class, in case of this annotation we need to use @ResponseBody explicitly.
  • This annotation used with presentation layer i.e controller classes(people also prefer to call endpoint).
  • internal implementation.
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

}

 

 

Note – In the interview, you may be asked what is the difference between  @Component, @Service, and @Repository.  @Service and @Repository is a special form of @Component. @Service annotation used with Service layer classes and @Repository used with the persistent layer. @Component we can use either service layer or persistent layer but we generally avoid since we have separate annotations for both(@Service and @Repository). If we look declaration of @Service and @Repository both are internally annotated with @Component. Again what is the difference between these annotations, functionally there is no difference. If you use @Component instead of @Repository and @Service it will work fine but since we have difference annotations for a different purpose why we should not use to proper place. It will make our classes more readable. Apart from that @Repository supports exception translation functionality.

 

How to use these annotations.

@Component – Suppose we have a class in our application EncryptDecryptPassword.java where we have logic for encryption and decryption. This class we can annotate with @Component.

@Component
public class EncryptDecryptPassword {
 //some more logic
}

@Service – Any service layer class where we have business logic. For example BookServiceImpl.java

@Service("bookServiceImpl")
public class BookServiceImpl implements BookService{
//some more logic	

}

@Repository – Any persistent layer which is going to communicate with the database. For example – BookRepository.java

@Repository
public interface BookRepository extends CrudRepository<Book,Serializable> {
	//some more logic
}

 

@Controller – Any presentation layer i.e controller classes/endpoint.

@Controller
@ResponseBody
public class BookController {
	// some more logic
}

 

Note  – @Controller, @Service, and @Repository derived from @Component.

@Component @Controller @Service and @Repository annotations example using spring boot

 

@Component @Controller @Service and @Repository annotations example using spring boot example.

Create maven project, Don’t forget to check ‘Create a simple project (skip)’click on next. Fill all details(GroupId – pathvariableexample, ArtifactId – pathvariableexample and name – pathvariableexample) and click on finish. Keep packaging as the jar.

 

Modify the pom.xml with below code.

<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>springdataexample</groupId>
  <artifactId>springdataexample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springdataexample</name>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
 </parent>
  <dependencies>
	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency> -->
        
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0</version>
        </dependency>
   </dependencies>
   
   
   
   
   
   <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <start-class>com.springdata.springdataexample.SpringDataExampleUsingOracle</start-class>
        <java.version>1.8</java.version>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.springdata.springdataexample.SpringDataExampleUsingOracle</mainClass>
                </configuration>
            </plugin>
			<plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <fork>true</fork>
                <executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
            </configuration>
        </plugin>
        </plugins>
    </build>
   
    
   
 </project>

 

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

Let maven download all necessary jar. Once it is done we will able to see maven dependency folder which contains different jar files.

We can start to write our controller classes, ServiceImpl and Repository. The folder structure of application-

 

Step 6 – Define main class SpringDataExampleUsingOracle.java

SpringDataExampleUsingOracle.java

package com.springdata.springdataexample;

import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication(scanBasePackages={"com.springdata"})
@EntityScan("com.springdata.*") 
public class SpringDataExampleUsingOracle {
	
	
	public static void main(final String[] args) {
		final ConfigurableApplicationContext configurableApplicationContext = SpringApplication
				.run(SpringDataExampleUsingOracle.class, args);
		
		
	}
	
	@Bean
	public SessionFactory sessionFactory(final HibernateEntityManagerFactory hemf) {
		return hemf.getSessionFactory();
	}	
}

 

Step 7 – Define entity class i.e Book.java

Book.java

package com.springdata.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "book")
public class Book {
	 
	 @Id
	 @GeneratedValue(strategy = GenerationType.AUTO)
	 private int bookId;
	 
	 @Column(name="book_name")
	 private String bookName;

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}

	
	 
	 
}

Step 8 – Define repository interface extending CrudRepository.

BookRepository.java

package com.springdata.repository;


import java.io.Serializable;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;

import org.springframework.stereotype.Repository;

import com.springdata.entity.Book;

@Repository
public interface BookRepository extends CrudRepository<Book,Serializable> {
	public Book findByBookId(int bookId);
}


 

Step 9 – Define service interface i.e BookService.java

BookService.java

package com.springdata.service;

import org.springframework.stereotype.Component;

import com.springdata.entity.Book;
@Component
public interface BookService {
	public Book findByBookId(int bookId);
}

Step 10 – Define service impl class.

BookServiceImpl.java

package com.springdata.serviceimpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.springdata.entity.Book;
import com.springdata.repository.BookRepository;
import com.springdata.service.BookService;
@Service("bookServiceImpl")
public class BookServiceImpl implements BookService{
	
@Autowired
private BookRepository bookRepository;
@Override
public Book findByBookId(int bookId) {
	Book book = bookRepository.findByBookId(bookId);
	return book;
}

}

 

Step 11 – Define controller class.

BookController.java

package com.springdata.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.springdata.entity.Book;
import com.springdata.service.BookService;

@RestController
@RequestMapping("/book")
public class BookController {
	@Autowired
	private BookService bookService;
	
	@RequestMapping(value = "/getBook",method = RequestMethod.GET)
    @ResponseBody
    public Book getPassengerDetails(int bookId) {
		Book bookResponse = bookService.findByBookId(bookId);
		
		return bookResponse;
	}
}

 

Step 12 – Define JpaConfig class.

JpaConfig.java

package com.springdata.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableJpaRepositories(basePackages = "com.springdata.repository")

public class JpaConfig {

}

 

Step 13 – Define application.properties file

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# Show or not log for each sql query
spring.jpa.show-sql = true


spring.jpa.hibernate.ddl-auto =update




spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect

server.port = 9091

 


spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

 

That’s all about @Component @Controller @Service and @Repository annotations example using spring boot.

You may like.

 

Check @Service annotation docs.