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
  • Contact Us

Spring Annotations [Quick Reference]

June 19, 2019 by itadmin Leave a Comment

Below is the summary of the spring annotations that people use most frequently across spring applications. Spring Framework 2.5 added the annotations to the framework.

Before that, the XML files defined every configuration. Annotations became more convenient to reduce the XML configuration files and annotate the classes and methods with different annotations used at the time of scanning the files in the classpath.

Quick Reference for Spring Annotations

In this tutorial, I will list down the essential spring annotations used in Spring Core, Spring MVC, Spring Boot, Spring Data JPA, etc. modules previously published in this blog. I will continuously update this reference when I am writing the tutorial for new annotations.

You can bookmark this tutorial for quick reference of the most important annotations used in spring applications.

Spring Annotations Reference

Annotations Description
@Component, @Repository, and @Service @Component annotation is the generalized form considered as a candidate for auto-detection when using annotation-based configuration and classpath scanning. It extended to more specific forms such as @Controller, @Repository, and @Service.
@Autowired The XML files define string bean dependencies, and the same can be automatically detected by the Spring container by using the @Autowired annotation. This would eliminate the use of XML configurations.
@Qualifier There may be scenarios when you create more than one bean of the same type and want to wire only one of them with a property. Control this using @Qualifier annotation along with the @Autowired annotation.
@Required @Required annotation applies to bean property setter methods and enforces required properties
Difference between @Resource, @Autowired, and @Inject This tutorial explains the difference between these three annotations @Resource, @Autowired and @Inject used for injecting the objects.
@Inject and @Named @Inject and @Named annotations are JSR-330 annotations were introduced in Spring 3 as an alternative for the spring annotations @Autowired and @Component.
@Resource, @PostConstruct, and @PreDestroy This tutorial explains the JSR-250 annotations that Spring 2.5 introduces, which include @Resource, @PostConstruct, and @PreDestroy annotations.
@RestController @RestController annotation is inherited from the @Controller annotation. This is the special version of @Controller annotation for implementing the RESTful Web Services. @RestController was added as part of the Spring 4 release.
@RequestHeader @RequestHeader annotation for facilitating us to get the header details easily in our controller class. This annotation would bind the header details with the method arguments, and it can be used inside the methods.
@ControllerAdvice @ControllerAdvice annotation used for defining the exception handler with specific exception details for each method. This component will handle any exception thrown on any part of the application.
@ModelAttribute @ModelAttribute annotation can be used as the method arguments or before the method declaration. The primary objective of this annotation to bind the request parameters or form fields to a model object.
@Conditional This tutorial explains one of the new features introduced in spring 4, conditional annotation type.
@Query This spring data series tutorial explains @query annotation and how to create a custom query using the @query annotation.
@Profile This tutorial explains how to enable profiles in your spring application for different environments.
@Configuration Instead of using the XML files, we can use plain Java classes to annotate the configurations by using the @Configuration annotation. If you annotate a class with @Configuration, it indicates that the class defines the beans using the @Bean annotation.
@PathVariable We have to use @PathVariable for accepting the customized or more dynamic parameters in the request paths.
@Controller, @RequestMapping, @RequestParam, @SessionAttributes, and @InitBinder This tutorial explains some of the key annotations that are related to Spring MVC applications @Controller, @RequestMapping, @RequestParam, @SessionAttributes, and @InitBinder
Difference between @RequestParam and @PathVariable This tutorial explains the difference between the two annotations @RequestParam and @PathVariable.
@RequestMapping You can use @RequestMapping annotation for mapping web requests to particular handler classes or handler methods.
@Value  This tutorial shows how to load the properties file values using the @Value annotation.
@Import @Import is the annotation used for consolidating all the configurations defined in various configuration files using @Configuration annotation.
@Transactional Use annotation @Transactional to define a particular method that should be within a transaction.
@SpringBootApplication This is annotation is the heart of spring boot application. @SpringBootApplication indicates that it is the entry point for the spring boot application.
@EnableAutoConfiguration This example demonstrates how to use the @EnableAutoConfiguration annotations for auto-configuring the spring boot applications.
@EnableCaching @EnableCaching annotation is the annotation-driven cache management feature in the spring framework. This annotation added to the spring in version 3.1.

I will be adding more tutorials on annotations on this page. The above list will be updated frequently to reflect the latest spring annotations in the framework. If you are interested in receiving the updates on spring framework, please subscribe here.

Thank you for reading my blog!! Happy Learning!! If you have any questions related to spring development, please drop a comment or send me a mail. I will try my best to respond to your queries.

Filed Under: Spring Framework Tagged With: Spring Annotations, XML files

@RequestMapping Annotation in Spring MVC

March 22, 2016 by Krishna Srinivasan Leave a Comment

@RequestMapping annotation is used for mapping web requests to particular handler classes or handler methods. The classes or methods that are annotated with @RequestMapping will be scanned and registered as the URI mappings for that specific class or method. Any future web requests will be redirected to that class or method. This annotation is part of Spring MVC module.

Also Read:

  • Spring Boot Tutorials
  • Spring Data JPA Tutorials

This annotation can be used in class level or method level. If you are using at the class level, that will be set as the common relative path for all the methods inside the class. If you are using at the only method level, each will be acting as its own relative path from the application’s context root. This tutorial has examples to makes you understand the difference when you are annotating at the class level and method level.

RequestMapping in Spring MVC
RequestMapping in Spring MVC

RequestMapping Annotation Parameters

The following are the parameters accepted by this annotation:

  • consumes: This argument narrows down the acceptable media format from the request.
  • headers: The headers of the mapped request, narrowing the primary mapping.
  • method: This argument specifying the HTTP methods can be redirected to that method. More than one can be specified by separating using commas. The HTTP methods that are used are GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE
  • name: This is simply a name to the mapping. This can be specified at the class level and the method level. If you specify at both the levels, then a combined name is derived by concatenation with “#” as a separator.
  • params: The parameters of the mapped request, narrowing the primary mapping.
  • path: This is an alias for the value argument. the path mapping URIs (e.g. “/myPath.do”). Ant-style path patterns are also supported (e.g. “/myPath/*.do”). At the method level, relative paths (e.g. “edit.do”) are supported within the primary mapping expressed at the type level.
  • produces: This argument narrows down the returned media format to the response.
  • value: This is the primary mapping used for mapping the web request to that method.

Class Level Mapping

If you declare @RequestMapping at the class level, the path will be applicable to all the methods in the class. Let’s look at the following example code snippet:

[code lang=”java”]
@Controller
@RequestMapping("/millets")
public class SpringMVCController {
@RequestMapping(value="/foxtail")
public String getFoxtail(){
return "foxtail";
}
@RequestMapping(value="/finger")
public String getFinger(){
return "finger";
}
public String getCommon(){
return "common";
}
}
[/code]

In the above code, the relative path /millets is enforced to all the methods inside the class. The method getFoxtail() will be invoked when user enter the URI /millets/foxtail. However, the last method getCommon() will not be invoked by any request because this method is not annotated with the @RequestMapping annotation.

Method Level Mapping

When there is no class level mapping and multiple method-level mappings are defined, each method would form a unique relative path. Let’s look at the below example code:

[code lang=”java”]
@Controller
public class SpringMVCController {
@RequestMapping(value="/foxtail")
public String getFoxtail(){
return "foxtail";
}
@RequestMapping(value="/finger")
public String getFinger(){
return "finger";
}
}
[/code]

In the above code, both the method have their individual relative paths /foxtail and /finger respectively.

HTTP Methods Mapping

One of the other ways to do the Request Mapping is to use the HTTP methods. You can specify in the @RequestMapping annotation that for which HTTP method request the method has to be invoked. Let’s look at the following code:

[code lang=”java”]
@Controller
public class SpringMVCController {
@RequestMapping(value="/foxtail",method=RequestMethod.GET)
public String getFoxtail(){
return "foxtail";
}
@RequestMapping(value="/foxtail",method=RequestMethod.POST)
public String getList(){
return "foxtailList";
}
@RequestMapping(value="/",method=RequestMethod.GET)
public String getMillets(){
return "millets";
}
}
[/code]

In the above code, if you look at the first two methods of mapping to the same URI, but both have the different HTTP methods. The first method will be invoked when HTTP method GET is used and the second method is invoked when HTTP method POST is used. This kind of design is very useful for writing the REST APIs for your project.

Mapping using Params

Another very useful mapping technique is to use the parameters in the query string to filter the handler mappings. For example, you can restrict the handler mapping by configuring like if the URL query string has this parameter then go to this method or redirect to some other method.

Let’s look at this example snippet:

[code lang=”java”]
@RequestMapping(value="/millets",method=RequestMethod.GET,params="foxtail")
public String getFoxtail(){
return "foxtail";
}
[/code]

In the above example code, the request goes to this method only when the following criteria are satisfied:

  1. If the URL is /millets and
  2. If the HTTP method is GET and
  3. If the query request has the parameter with the name foxtail

Summary

In this tutorial, I have explained how to use the @RequestMapping annotation in your spring MVC application. The various combinations like class level mapping, method level mapping, params matching, HTTP methods matching, headers mapping and multiple paths URI mappings.

If you have any questions on how to use @RequestMapping annotation and any related spring mMVCissues, please feel free to drop a comment in this tutorial for any help.

Thank you for reading my tutorial!! Happy Learning!!

Filed Under: Spring Framework Tagged With: Spring Annotations

Difference Between @RequestParam and @PathVariable in Spring MVC

March 20, 2016 by Krishna Srinivasan Leave a Comment

@RequestParam and @PathVariable

@RequestParam and @PathVariable annotations are used for accessing the values from the request. Both the the annotations have the significant purpose and use respectively. The key difference between @RequestParam and @PathVariable is that @RequestParam used for accessing the values of the query parameters where as @PathVariable used for accessing the values from the URI template.

In this tutorial I will explain the @RequestParam and @PathVariable annotations used in Spring MVC with a simple example and syntax used for accessing the values from query string and URI template.

@RequestParam vs @PathVariable Tutorial
@RequestParam vs @PathVariable Tutorial

@RequestParam

@RequestParam annotation used for accessing the query parameter values from the request. Look at the following request URL:

[code]
http://localhost:8080/springmvc/hello/101?param1=10&param2=20
[/code]

In the above URL request, the values for param1 and param2 can be accessed as below:

[code lang=”java”]
public String getDetails(
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
…
}
[/code]

The following are the list of parameters supported by the @RequestParam annotation:

  • defaultValue – This is the default value as a fallback mechanism if the request is not having the value or it is empty.
  • name – Name of the parameter to bind
  • required – Whether the parameter is mandatory or not. If it is true, failing to send that parameter will fail.
  • value – This is an alias for the name attribute

@PathVariable

@PathVariable identifies the pattern that is used in the URI for the incoming request. Let’s look at the below request URL:

[code]
http://localhost:8080/springmvc/hello/101?param1=10&param2=20
[/code]

The above URL request can be written in your Spring MVC as below:

[code lang=”java”]
@RequestMapping("/hello/{id}")
public String getDetails(@PathVariable(value="id") String id,
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
…….
}
[/code]

The @PathVariable annotation has only one attribute value for binding the request URI template. It is allowed to use the multiple @PathVariable annotation in the single method. But, ensure that no more than one method has the same pattern.

While developing RESTful Web Services, it will be useful to use this annotation for forming the more flexible URI (Also Read : REST API Best Practices).

@PathParam vs @QueryParam

If you want to understand the difference between @PathParam and @QueryParam, the above two annotations are defined in JAX-RS implementations for the exact purpose of @PathVariable and @RequestParam which is defined in spring’s REST implementations. But, you could use either of the annotations without any difference in the behavior.

RequestParam vs PathVariable Example

Difference Between @RequestParam and @PathVariable in Spring MVC
RequestParam vs PathVariable

Here is the complete source code for the example that demonstrates the key difference between RequestParam and PathVariable annotations. I have used Spring Boot for writing this example application. If you feel I have missed any key points about the RequestParam and PathVariable, please write it in the comments section.

SpringMVCController.java

[code lang=”java”]
package net.javabeat.spring.boot.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class SpringMVCController {
@RequestMapping("/hello/{id}")
public String getDetails(@PathVariable(value="id") String id,
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
System.out.println("ID : " + id);
System.out.println("Param 1 : " + param1);
System.out.println("Param 2 : " + param2);
return "hello";
}
}

[/code]

Application.java

[code lang=”java”]
package net.javabeat.spring.boot.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

[/code]

WebMvcConfig.java

[code lang=”java”]
package net.javabeat.spring.boot.example.controller;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter{
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/");
resolver.setSuffix(".jsp");
return resolver;
}
}

[/code]

application.properties

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

pom.xml

[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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.javabeat</groupId>
<artifactId>boot</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>boot</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<finalName>boot</finalName>
</build>
</project>
[/code]

If you don’t know how to run this application, please read our spring boot tutorial to understand how to run a spring boot application.

Download Source Code

[wpdm_package id=’23325′]

Summary

This tutorial would have helped you to understand the difference between @PathVariable and @RequestParam in the Spring MVC. Also, I have clarified about the alternative annotations @PathParam and @QueryParam which are supported in the official JAX-RS implementations. If you have any questions, please write it in the comments section.

Thank you for reading my blog. Happy Reading!!

Filed Under: Spring Framework Tagged With: @PathVariable, @RequestParam, Application.java, Spring Annotations, SpringMVCController.java, WebMvcConfig.java

@EnableCaching Annotation in Spring

March 17, 2016 by Krishna Srinivasan Leave a Comment

@EnableCaching annotation is the annotation-driven cache management feature in the spring framework. This annotation has been added to the spring since the version 3.1. If you are using this annotation, then you are not required to write the XML bean definitions for cache manager.

@EnableCaching in Spring Framework
@EnableCaching in Spring Framework

When you annotate your configuration class with @EnableCaching annotation, this triggers a post processor that would scan every Spring bean for the presence of caching annotations on public methods. If such an annotation is found, a proxy is automatically created to intercept the method call and handle the caching behavior accordingly.

If you are interested in reading more about the caching, please read my tutorial on spring caching. This tutorial helps you to understand the use of @EnableCaching annotation in spring. If you have any questions, please write it in the comments section.

Here is a simple example that demonstrate the use of @EnableCaching functionality. In the below code, I am trying to cache a method in the Book class.

@EnableCaching Example

Book.java

[code lang=”java”]
import org.springframework.cache.annotation.Cacheable;

public class Book {
@Cacheable(value = { "sampleCache" })
public String getBook(int id) {
System.out.println("Method executed..");
if (id == 1) {
return "Book 1";
} else {
return "Book 2";
}
}
}
[/code]

CachingConfig.java

[code lang=”java”]
import java.util.Arrays;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CachingConfig {
@Bean
public Book book() {
return new Book();
}

@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("sampleCache")));
return cacheManager;
}
}
[/code]

The above Java Configuration is equivalent of writing the following XML configurations in your spring configuration file:

[code lang=”xml”]
<beans>
<cache:annotation-driven/>
<bean id="book" class="Book"/>
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
<property name="name" value="sampleCache"/>
</bean>
</set>
</property>
</bean>
</beans>
[/code]

EnableCachingAnnotationExample.java

[code lang=”java”]
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class EnableCachingAnnotationExample {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(CachingConfig.class);
ctx.refresh();
Book book = ctx.getBean(Book.class);
// calling getBook method first time.
System.out.println(book.getBook(1));
// calling getBook method second time. This time, method will not
// execute.
System.out.println(book.getBook(1));
// calling getBook method third time with different value.
System.out.println(book.getBook(2));
ctx.close();
}
}
[/code]

If you run the above program, you will get the following output:

[code]
Method executed..
Book 1
Book 1
Method executed..
Book 2
[/code]

@EnableCaching Parameters

Most of the time you have to use the @EnableCaching annotation without any parameters. But, this annotation provides three parameters:

  • mode – This parameter indicates how caching advice should be applied.
  • order – This parameter specifies the ordering of the execution of the caching advisor when multiple advices are applied at a specific joinpoint (Also Read : AOP in Spring.
  • proxyTargetClass – This parameter indicates whether subclass-based (CGLIB) proxies are to be created as opposed to standard Java interface-based proxies.

Filed Under: Spring Framework Tagged With: Spring Annotations

@Profile Annotation in Spring 4

July 3, 2015 by Krishna Srinivasan Leave a Comment

This tutorial explain how to enable profiles in your spring application for different environments. Also this tutorial explains the new improvements in the Spring 4.0 release and how it is different from the older releases.

If you are working for a real time projects, it is often basic requirement to have the different environments like development, testing and production. In this scenario, the underlying resources (ie, database, file system, etc) for each environment would be different. The challenges arises when you want to move your source code to different environments. You would have to adjust the configurations to point to new environment details like Database, etc. The solution for the above problem is to create different profiles for each environment and enable them when you move to another environment.

List of Spring Tutorials : Spring Tutorial

@Profile annotation is introduced as part of the Spring Framework 3.1 release. @Profile annotation helps developers to create multiple configurations details for different environments. Prior to Spring 4, only bean level annotation is supported by @Profile. With Spring 4, this can be used in the method level. That gives more control and eliminate the need for creating multiple configuration files. This tutorial provide simple example for @Profile annotation.

Spring official document defines @Profile as:

Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments.

I have written a very simple example to demonstrate the power of @Profile feature in Spring 4. This example declares data source for dev and prod. By using the @Profile annotation, a suitable data source will be invoked by the test class.

@Profile Annotation in Spring 4

@Profile Annotation

The syntax for this annotation is @Profile(“dev”). If a bean or method marked with annotation will be associated with that particular profile name. This example uses the method type annotation (Spring 4 improvements). Where as you also do it in the class level.

@ActiveProfiles Annotation

How do we tell the container that which profile is active now to pick up the right configurations. We have to use @ActiveProfiles to tell the currently active profile. This can be done through XML, JavaConfig, Annotations and Programatically.

Annotation Configuration

[code lang=”java”]
@ActiveProfiles(profiles = "dev")
public class DevConfigTest {
//code here
}
[/code]

Web.xml Configuration

[code lang=”java”]
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>DOUBLEUPMINT</param-value>
</context-param>
[/code]

Programatic Configuration

[code lang=”java”]
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//Enable a "live" profile
context.getEnvironment().setActiveProfiles("live");
[/code]

@Profile Annotation Example

Here is the example application using @Profile annotation.

Student.java

[code lang=”java”]
package javabeat.net.spring.core;

public class Student {
private String id;
private String name;
private String grade;

public Student(String id, String name, String grade){
this.id = id;
this.name = name;
this.grade = grade;
}

public String getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getGrade() {
return grade;
}

public void setGrade(String grade) {
this.grade = grade;
}

}
[/code]

DevEnvConfig.java

[code lang=”java”]
package javabeat.net.spring.core;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile("dev")
public class DevEnvConfig {
@Bean
public Student user(){
return new Student("001", "Dev Student 1","Grade 1");
}
}
[/code]

ProdEnvConfig.java

[code lang=”java”]
package javabeat.net.spring.core;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile("prod")
public class ProdEnvConfig {
@Bean
public Student user(){
return new Student("002", "Prod Student 1","Grade 2");
}
}
[/code]

ProductionDataSourceConfig.java

[code lang=”java”]
package javabeat.net.spring.core;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile("prod")
public class ProductionDataSourceConfig {
@Bean
public DataSource dataSource(){
//Do connection related task
return null;
}
}
[/code]

SpringProfileTest.java

[code lang=”java”]
package javabeat.net.spring.core;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringProfileTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("prod");
ctx.scan("javabeat.net.spring.core");
ctx.refresh();
Student student = ctx.getBean(Student.class);
System.out.println("\nStudent Id:" + student.getId() + ", \nStudent Name:" + student.getName()
+ ", \nStudent Grade : " + student.getGrade());
}
}
[/code]

Summary

This tutorial demonstrated how to use @Profile annotation in your project. It is a simple example and I hope this helps you to understand the concepts. If you have any questions, please write it in the comments section.

Filed Under: Spring Framework Tagged With: Spring Annotations

Spring MVC Annotations : @Component, @Repository, @Service

June 28, 2015 by Krishna Srinivasan Leave a Comment

This tutorial explains the advantage of using the spring mvc annotations @Component, @Repository and @Service and how to use them. 

Spring Annotations are one of the nice feature to configure the Spring MVC applications. There are wide variety of annotations are define in the Spring Framework. In our earlier tutorials many of the most widely used annotations are explained with more details. Some of them are @Autowired, @Qualifier, @ControlAdvice and @RestController. In this tutorial I would explain the some more spring mvc annotations @Component, @Repository and @Service.

Since Spring Framework 2.5, annotations has been added to Spring Framework as the alternative to the XML configurations. There is more features added in Spring 3.0 like component scanning which automatically scan the packages and load the beans.

  • Also Read : Most Popular Spring Tutorials

@Component

Spring Component Annotations

This annotation tells the spring container to pick the bean while component-scanning is running. It is more generalized form of the annotations and can be used for any type of beans to inform the component-scanning mechanism. The declaration would look like this:

[code lang=”java”]
@Component("studentDAO")
public class StudentDAOImpl implements StudentDAO{
public StudentDTO createStudent(){
//code here
}
}
[/code]

In reality, @Component annotation is very rarely used since other specialized annotations  @Service, @Repository and @Controller can be used.

@Repository

@Repository is specialized implementation of @Component for indicating the Data Access Objects (DAO). Advantage of using the @Repository annotation, importing the DAOs into the DI container and also this annotation makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

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

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

//@Component("studentDAO") – This also correct
@Repository("studentDAO")
public class StudentDAOImpl implements StudentDAO{
//code here
}
}
[/code]

@Service

This another specialized version of @Component to inform the spring component-scanning mechanism to load the service classes. These are introduced to in the spring framework to add any specific features to the service classes in the future. The declaration of @Service annotation would be:

[code lang=”java”]
<pre>package javabeat.net.spring;

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

//@Component("studentManager") – This also correct
@Service("studentManager")
public class StudentManagerImpl implements StudentManager{
//code here
}
}</pre>
[/code]

Spring MVC Annotations Example

Here is the complete working example using the annotations explained in the above sections. This example uses the spring mvc annotations @Component, @Repository and @Service.

StudentDTO.java

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

public class StudentDTO {
private String id;
private String name;
private String grade;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String toString(){
StringBuffer buffer = new StringBuffer();
buffer.append("\nStudent Id : " + this.id);
buffer.append("\nStudent Name : " + this.name);
buffer.append("\nStudent Grade : " + this.grade);
return buffer.toString();
}
}

[/code]

StudentDAO.java

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

public interface StudentDAO {
public StudentDTO createStudent();
}

[/code]

StudentDAOImpl.java

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

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

//@Component("studentDAO") – This also correct
@Repository("studentDAO")
public class StudentDAOImpl implements StudentDAO{
public StudentDTO createStudent(){
StudentDTO dto = new StudentDTO();
dto.setId("001");
dto.setName("Che");
dto.setGrade("First");
return dto;
}
}

[/code]

StudentManager.java

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

public interface StudentManager {
public StudentDTO createStudent();
}

[/code]

StudentManagerImpl.java

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

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

//@Component("studentManager") – This also correct
@Service("studentManager")
public class StudentManagerImpl implements StudentManager{
@Autowired StudentDAO studentDAO;
public StudentDTO createStudent(){
return studentDAO.createStudent();
}
}

[/code]

applicationContext.xml

[code lang=”java”]
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="javabeat.net" />
</beans>

[/code]

MainApp.java

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

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("javabeat/net/spring/applicationContext.xml");
StudentManager manager = (StudentManagerImpl)applicationContext.getBean("studentManager");
System.out.println((manager.createStudent()));
}

}

[/code]

Summary

I hope this example would have helped you to understand the basic use of @Component, @Service and @Repository spring mvc annotations. These are most widely used for the Spring MVC applications. Also please read our Most Popular Spring Tutorials. If you have any questions, please write it in the comments section. 

Filed Under: Spring Framework Tagged With: Spring Annotations

Spring : How To Load Properties File using @Value Annotation

May 3, 2014 by Krishna Srinivasan Leave a Comment

This example shows how to load the properties file values using the @Value annotation. Accessing the property file values in the Spring application involves the following steps:

  • Add the property file details to spring bean configuration file. You have to use the “classpath” prefix if you want to load the files from the classpath.
  • Create a properties file in the same name that is configured in the XML file and put it under the classpath folders. In most scenarios, source folders will be by default kept under the classpath.
  • Use @Value annotation to get the property valye. @Value annotation takes the string parameter which is “key” used in the properties file. This annotation has to be used with variables to inject the value.

Lets look at the following example code:

1. Spring MVC Configurations

spring4-mvc-dispatcher-servlet.xml

[code lang=”java”]
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">

<context:component-scan base-package="com.javabeat.controller" />
<context:property-placeholder location="classpath:application.properties"/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

</beans>
[/code]

2. Application Properties File

application.properties

[code lang=”java”]
msg=Spring Application Properties!!
[/code]

3. Spring MVC Controller

HelloController.java

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

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/welcome")
public class HelloController {
@Value("${msg}")
private String msg;

@RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("msg", this.msg);
return "hello";

}

}
[/code]

4. Views

hello.jsp

[code lang=”java”]
<html>
<body>
Your Message : ${msg}
</body>
</html>
[/code]

5. Web Deployment Descriptor

web.xml

[code lang=”java”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Spring MVC 4.0 Web Application</display-name>
<servlet>
<servlet-name>spring4-mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>spring4-mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
[/code]

6. Demo

If you run the above example, you would get the below output.

Spring Value Annotation

[wpdm_file id=82]

Filed Under: Spring Framework Tagged With: Spring Annotations

@Import Annotation in Spring Framework

October 28, 2013 by Krishna Srinivasan Leave a Comment

In my previous article I have explained about the JavaConfig in Spring 3.0. It is a new way of configuring the bean definitions without using the traditional XML files. Also I have listed the annotations defined as part of JavaConfig approach. If you are beginner in spring framework, we have huge collection of spring tutorials and spring 4 tutorials for your reference.

In the list, @Import is the one such annotation used for consolidating all the configurations defined in various configuration files using @Configuration annotation. It is much similar to how we import the different XML configuration files to a single file. @Import annotation will used for the same purpose. This tutorial explains how to use @Import for Importing JavaConfig Files in Spring Projects.

If you look at the below sample code, I have created two configuration files and then imported them to the main configuration file. At the end, I need to create contaxt using only the main configuration file. If you have any questions, please write it in the comments section.

Car.java

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

public interface Car {
public void print();
}

[/code]

Toyota.java

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

import org.springframework.stereotype.Component;

@Component
public class Toyota implements Car{
public void print(){
System.out.println("I am Toyota");
}
}
[/code]

Volkswagen.java

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

import org.springframework.stereotype.Component;

@Component
public class Volkswagen implements Car{
public void print(){
System.out.println("I am Volkswagen");
}
}
[/code]

JavaConfigA.java

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JavaConfigA {
@Bean(name="volkswagen")
public Car getVolkswagen(){
return new Volkswagen();
}
}
[/code]

JavaConfigB.java

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JavaConfigB {
@Bean(name="toyota")
public Car getToyota(){
return new Toyota();
}
}
[/code]

ParentConfig.java

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

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({JavaConfigA.class,JavaConfigB.class})
public class ParentConfig {
//Any other bean definitions
}
[/code]

ContextLoader.java

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

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ContextLoader {
public static void main (String args[]){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ParentConfig.class);
Car car = (Toyota)context.getBean("toyota");
car.print();
car = (Volkswagen)context.getBean("volkswagen");
car.print();
context.close();
}
}
[/code]

If you run the above example,the printed output will be,
javaconfig spring import

In this tutorial I have explained how to use @Import annotation in your spring applications. This is very convenient way for importing multiple configuration files into a single parent configuration file instead of declaring all the configurations in a single file. I hope this example helped you. If you have any questions, please write it in the comments section.

Filed Under: Spring Framework Tagged With: Spring Annotations

@Configuration Annotation in Spring 3.0

October 27, 2013 by Krishna Srinivasan Leave a Comment

Spring 3.0 has introduced new way for configuring the spring beans. In fact this option was maintained by spring framework separately as JavaConfig project. Later this project is merged to the spring core framework and all the features are directly accessible from the spring core. If you are beginner in spring framework, we have huge collection of spring tutorials and spring 4 tutorials for your reference.

Instead of using the XML files, we can use plain Java classes to annotate the configurations by using the @Configuration annotation. If you annotate a class with @Configuration annotation, it indicates that the class is used for defining the beans using the @Bean annotation. This is very much similar to the <bean/> element in the spring XML configurations.

Additional Reading:

  • Spring Boot Tutorials
  • Spring Data JPA Tutorial

This approach is not 100% replacement for the XML configurations. It is upto the developer’s choice to choose between JavaConfig and XML configurations. In most cases, the bootstrap configuration will be done using the XML file and then JavaConfig will be used for adhoc requirements.

The following are the list of annotations introduced as part of the JavaConfig module.

  1. @Configuration
  2. @Bean
  3. @DependsOn
  4. @Primary
  5. @Lazy
  6. @Import
  7. @ImportResource
  8. @Value

In this example I have used only the first two annotations to demonstrate the basic use of JavaConfig features.

AnnotationConfigApplicationContext is the class used for loading the configuration from Java class file. Look at the below example. If you have any questions, please write it in the comments section.

1. Create JavaConfig

The following are the twp steps required for creating the Java configuration classes in the spring framework.

  • Annotate the class with @Configuration annotation
  • Annotate the method with @Bean to indicating that it is bean definition

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JavaConfig {
@Bean(name="userDetails")
public UserDetails userDetails(){
return new UserDetails();
}
}
[/code]

2. Create Bean Class

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

public class UserDetails {
private String name;
private String phone;
private String city;
private String country;

// Other methods

}
[/code]

3. Load Application Context and Instantiate Bean

Create AnnotationConfigApplicationContext and get the bean instance. This is very simple example to show you how simple to configure the beans using Java class.

[code lang=”java”]

package javabeat.net;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class JavaConfigDemo {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
UserDetails userDetails = (UserDetails) context.getBean("userDetails");
}
}

[/code]

I hope this article have helped you to understand the use of @Configuration annotation and how to use them. This has been taken as the recommended way for writing the configurations for spring applications.

Filed Under: Spring Framework Tagged With: Spring Annotations

Transaction Control Using Annotations in Spring Framework

September 2, 2013 by Manisha Patil Leave a Comment

In this article I’ll discuss the use of the Spring Framework Transactions, to make the application more secure and without inconsistencies. But before you initiate a transaction in Spring, let’s first understand what are transactions. The transaction concept can be described with the acronym ACID. 1. Atomicity:- A transaction must be treated as a single operation, this means that all commands in this transaction can be completed successfully or unsuccessfully. Nothing will be saved if at least one command 100 goes wrong, everyone should run successfully without errors. 2. Consistency: This is the consistency of integrity of the database, they are: unique and primary keys etc. 3. Isolation: Many transaction can be executed at the same time, the insulation ensures that each transaction is isolated from the other, thereby preventing data corruption. 4. Durability: A transaction should continue after being persisted and can not be deleted by system failures.

Transactions with Spring Framework

Once you understand the concept, we should also keep in mind that there are two ways to work with transactions in an application: Programmatically or  Declaratively. Working Programmatically brings immense flexibility to manage their transactions, but the maintainability of the code becomes difficult and costly. On the other hand, working Decoratively is more stylish and follows good programming practices, since you’ll be separating completely the control of transaction of business rules. When it comes to Spring Framework you can work decoratively via XML or annotations, but in this article we will focus on the notes.

spring framework

Before you start using the transactions you need to tell Spring that you want to perform a transaction control via annotations, this is done through configuration shown in Listing 1 in the file applicationContext.xml.

Listing 1 : Enabling transactions via annotations in applicationContext.xml

[java]
<tx:annotation-driven transaction-manager="transactionManager"/>
[/java]

After this you will be able to use annotation @Transactional in order to define a particular method that should be within a transaction.

Isolation

The first parameter is Isolation, this can be defined as follows:

Listing 2 : Isolation Level

[java]
@ Transactional (isolation = Isolation.READ_COMMITTED)
[/java]

The possible types of isolation are:

  • ISOLATION_DEFAULT: Isolation level standard.
  • ISOLATION_READ_COMMITTED: Prevents just “dirty reads”.
  • ISOLATION_READ_UNCOMMITED: Indicates “dirty reads”, “non-repeatable reads” and “Phatom reads” may occur, or will not be prevented.
  • ISOLATION_REPEATABLE_READ: Prevents just “dirty reads” and “non-repeatable reads.”
  • ISOLATION_SERIALIZABLE: Prevents “dirty reads”, “non-repeatable reads” and “Phatom reads.”

My focus is not to teach the background operation of transaction, but only how its applied to Spring. I will briefly explain types of readings prevented in Isolation.

  • Dirty Read : This occurs when a transaction writes an X value and a transaction value B read this without having done the transaction commit or rollback the transaction. The case of a transaction rollback, the value of the transaction B read becomes invalid.
  • Non-repeatable read : Occurs when a single transaction in a line is read twice and the values ​​of these two readings are different.
  • Read Phatom : This occurs when two similar queries are executed and the result of the latter is different from the first.

Defining Propagation

Another very important parameter to be defined in a transaction in Spring is how transaction will be held. Here are the possible ways of propagation:

  • PROPAGATION_MANDATORY: Forces the use of a transaction, if there is no current transaction, an exception is thrown.
  • PROPAGATION_NESTED: Execute within a nested transaction if a current transaction exists.
  • PROPAGATION_NEVER: Prevents the use of a transaction. If there is a current transaction, an exception is thrown.
  • PROPAGATION_NOT_SUPPORTED: It uses the current transaction. This always runs with no transaction.
  • PROPAGATION_REQUIRED: Uses the current transaction if exists does not exist creates a new transaction.
  • PROPAGATION_REQUIRES_NEW: Creates a new transaction, if there is already a current stops this.
  • PROPAGATION_SUPPORTS: Uses the current transaction if one exists, otherwise executes without transaction.

There is a parameter “readOnly” in the @Transactional annotation. This specifies that no operation can be performed like DML (Insert, Update or Delete), ie only queries can be performed.

In Listing 3 we have defined a class that uses Spring’s transaction control, this uses a readOnly = false and PROPAGATION_REQUIRED, so always ensure that the Save method will run within a transaction.

Listing 3 : Using @Transactional practice

[java]
@ Repository
public class implements ProductDAOImpl ProductDAO {
private SessionFactory sessionFactory;

@ Autowired
public ProductDAOImpl (SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

private Session currentSession () {
sessionFactory.getCurrentSession return ();
}

@ Override
@ Transactional (propagation = Propagation.REQUIRED, readOnly = false)
public void save (ProductTech product) {
currentSession (.) save (product);
System.out.println ("product saved with sucess");
}
}
[/java]

The other annotations such as @Autowired and @Repository settings are also Spring annotations, which will not be focused in this article. As you can see in the “save” method we have defined the transaction as PROPAGATION_REQUIRED, therefore if we had 10 saves in the save, everyone should be required to succeed in their implementation, otherwise a rollback would be done.

Summary

Reference:

  • Managing transactions in EJB 3.0
  • Spring Auto scanning components
  • Introduction to Java Persistence API(JPA)

This article aims at practical use and fast Transaction, once you finish this reading you are able to use this feature of Spring. If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook.

Filed Under: Spring Framework Tagged With: Spring Annotations

  • 1
  • 2
  • Next Page »

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