Spring Data REST Java Configuration Example

Please refer to the earlier example using xml configuration.

This example shows how to implement spring data rest using java configuration without web.xml and spring config xmls. It also shows how to use H2 embedded in-memory database using spring java configuration.

Refer to my earlier post for the entity and repository classes. Also, delete src/main/webapp/WEB-INF/applicationContext.xml and src/main/webapp/WEB-INF/web.xml files as we would be using java configuration in this example.

Java equivalent for web.xml (WebAppInitializer.java)


package com.idodevjobs.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

@Configuration
public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext rootCtx = new AnnotationConfigWebApplicationContext();
        rootCtx.register(SpringMVCConfig.class);
        servletContext.addListener(new ContextLoaderListener(rootCtx));
        ServletRegistration.Dynamic reg = servletContext.addServlet("rest", RepositoryRestDispatcherServlet.class);
        reg.setLoadOnStartup(1);
        reg.addMapping("/api/*");
    }
}

Spring MVC Config (SpringMVCConfig.java)


package com.idodevjobs.example.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan("com.idodevjobs.example")
@Import({SpringDBConfig.class})
@EnableWebMvc
public class SpringMVCConfig {}

Spring DB Config (SpringDBConfig.java)


package com.idodevjobs.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("com.idodevjobs.example.repository")
public class SpringDBConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("com.idodevjobs.example.entity");
        entityManagerFactoryBean.setJpaProperties(jpaProperties());
        return entityManagerFactoryBean;
    }

    private Properties jpaProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.format_sql", "true");
        return properties;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        transactionManager.setDataSource(dataSource());
        return transactionManager;
    }
}

Servlet 3 Dependency (pom.xml)

Add the below dependency in pom.xml for servlet 3.0.


<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>

Using Servlet 3.0’s, ServletContainerInitializer class, the servlet container can be configured programmatically instead of the traditional web.xml.

Spring provides an implementation of ServletContainerInitializer, SpringServletContainerInitializer which is responsible for configuring the ServletContext using user-defined WebApplicationInitializer implementations.

About these ads
This entry was posted in java and tagged , , , , , , , , , , . Bookmark the permalink.

2 Responses to Spring Data REST Java Configuration Example

  1. Paul says:

    Why do we need to set transactionManager.setDataSource(dataSource()); in transactionManager() method when there is already entityManagerFactory set. Is it mandatory or just mistake?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s