Spring


How to force Spring Boot Security to say a little bit more?

By default spring boot security isn’t too talkative.
If you struggle with some problems and want to see what is going on under the covers, you can always switch to wider log level.

You can do it by providing this property in your application.yml or application.properties file.

logging.level.org.springframework.security: DEBUG

Additionaly you can turn on Spring Web debug logs and set debug parameter to true in your @EnableWebSecurity annotation

logging.level.org.springframework.web: DEBUG
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {...}

Spring test configuration example.

Hello.
Today I want to show you simple test configuration in spring mvc project.
In example I use java based configuration(I admit that this kind of configuration I prefer).
But in future I want to present xml based configuration, too.

On the bottom of the post you find link to github repository with full project.

Class under testing:

package com.raphaelsolarski.springtestconfig.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MyController {

    @RequestMapping(path = "/", method = RequestMethod.GET)
    String home() {
        return "home";
    }

}

Test:

package com.raphaelsolarski.springtestconfig.controller;

import com.raphaelsolarski.springtestconfig.config.WebConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebConfig.class}, loader = AnnotationConfigWebContextLoader.class)
@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class})
@WebAppConfiguration
public class MyControllerTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void getRootShouldReturnHomeView() throws Exception {
        mockMvc.perform(get("/")).andExpect(MockMvcResultMatchers.view().name("home"));
    }

}

github-icon Full code on github.com

Links:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html


Problem with spring @Value annotation. 1

Hi. Today I expirienced problem with @Value annotation in spring.
This annotation can be used to inject value from properties files in spring based applications.
I will show you a typical use case of this annotation, the problem I encountered and how I dealt with it.

foo.properties:

address=Warsaw

Foo.java:

package com.raphaelsolarski.value;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:foo.properties")
public class Foo {

    @Value("${address}")
    private String address;

    public String getAddress() {
        return address;
    }

}

FooTest.java:

package com.raphaelsolarski.value;

import com.raphaelsolarski.value.config.Config;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class FooTest {

    @Autowired
    private Foo foo;

    @Test
    public void shouldReturnPropertyValue() throws Exception {
        String actual = foo.getAddress();
        String expected = "Warsaw";
        Assert.assertEquals(expected, actual);
    }

}

The test will fail with the following error:

org.junit.ComparisonFailure: 
Expected :Warsaw
Actual   :${address}

There is a simple solution. We have to declare a PropertySourcesPlaceholderConfigurer bean somewhere in spring configuration of our application.

Config.java

package com.raphaelsolarski.value.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan("com.raphaelsolarski.value")
public class Config {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

github-icon Full code on github.com


How to add filter to spring mvc in java config? 1

In this post I show you how to add filter in two different kinds of spring based configurations.

Configuration by WebApplicationInitializer

package raphaelsolarski.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import raphaelsolarski.filter.MyFilter;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

public class MyWebAppInitializer implements WebApplicationInitializer {

   public void onStartup(ServletContext container) {
       //here I can set up any kind of spring context -> xml/java...
       AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
       appContext.scan("raphaelsolarski");
       ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
       registration.setLoadOnStartup(1);
       registration.addMapping("/");
       container.addFilter("My filter", MyFilter.class).addMappingForServletNames(null, false, "dispatcher");
       //or container.addFilter("My filter", MyFilter.class).addMappingForUrlPatterns(null, false, "/*");
   }

}

Configuration by AbstractAnnotationConfigDispatcherServletInitializer

package com.raphaelsolarski.config;

import com.raphaelsolarski.filter.MyFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;

public class MyDispatcher extends AbstractAnnotationConfigDispatcherServletInitializer{
   @Override
   protected Class<?>[] getRootConfigClasses() {
       return null;
   }

   @Override
   protected Class<?>[] getServletConfigClasses() {
       return new Class<?>[] {SpringConfig.class};
   }

   @Override
   protected String[] getServletMappings() {
       return new String[] {"/"};
   }

   @Override
   protected Filter[] getServletFilters() {
       return new Filter[] { new MyFilter() };
   }
}

How to configure dispatcher servlet without web.xml? 1

In my first post I want show you how to simply configure Dispatcher Servlet with Spring without xml code.
I will cover three types of spring configuration you may want to use(I think about cofiguration of rest of application, not about dispatcher servlet).
Java annotations driven config, xml based and mixture of both of them.

In configuration I will WebApplicationInitializer interface and AbstractDispatcherServletInitializer class.
When you want to configure dispatcher servlet in java you probably should use one of them.

Configuration by implementing WebApplicationInitializer interface:

import org.springframework.web.WebApplicationInitializer;

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        XmlWebApplicationContext appContext = new XmlWebApplicationContext();
        appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");

        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }

}

Configuration by extending AbstractDispatcherServletInitializer(for using xml based spring configuration):

public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {

    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }

    @Override
    protected WebApplicationContext createServletApplicationContext() {
        XmlWebApplicationContext cxt = new XmlWebApplicationContext();
        cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
        return cxt;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}

Configuration by extending AbstractAnnotationConfigDispatcherServletInitializer class(for java based spring configuration):

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { MyWebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}

Links:
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/WebApplicationInitializer.html
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-container-config