Tag Archives: IoC

mock Spring bean, encapsulate spring bean

How to encapsulate Spring bean

As far as I know Spring Framework doesn’t provide any mechanism to encapsulate Spring beans other than having separate contexts. So when you have public class registered in Spring’s Inversion of Control container, it can be autowired in any Spring bean from same context configuration. This is very powerful but it is also very dangerous. Developers can easily couple beans together. With lack of discipline team can easily shoot themselves in foot. Unfortunately I was working on one monolithic project where team was shooting themselves into foot with submachine gun. Wiring was breaking layering rules often. Nobody could easily follow what is dependent on what. Bean dependency graph was just crazy. This is serious concern in bigger applications.

Luckily there is one simple way how to encapsulate Spring bean. Spring works nicely with default access modifier on class level. So you can create package private bean, which can be used only within current package. Simple and powerful. Let’s take a look at example:

package net.lkrnac.blog.spring.encapsulatebean.service;

import org.springframework.stereotype.Service;

@Service
class AddressService {
	public String getAddress(String userName){
		return "3 Dark Corner";
	}
}

This simple bean is wired into another one within same package:

package net.lkrnac.blog.spring.encapsulatebean.service;

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

@Service
public class UserService {
	private AddressService addressService;

	@Autowired
	public UserService(AddressService addressService) {
		this.addressService = addressService;
	}
	
	public String getUserDetails(String userName){
		String address = addressService.getAddress(userName);
		return String.format("User: %s, %s", userName, address);
	}
}

Main context just scans both beans:

package net.lkrnac.blog.spring.encapsulatebean;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
}

Here is test to prove it works fine:

package net.lkrnac.blog.spring.encapsulatebean;

import net.lkrnac.blog.spring.encapsulatebean.service.UserService;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
	@Autowired
	private UserService userService;
	
	@Test
	public void isPackagePrivateBeanCalled(){
		//GIVEN - spring context defined by Application class
		
		//WHEN
		String actualUserDetails = userService.getUserDetails("john");
		
		//THEN
		Assert.assertEquals("User: john, 3 Dark Corner", actualUserDetails);
	}
}

I believe everybody should consider using default access modifier for every new bean. Obviously there would need to be some public bean within each package. But at not every bean. Source code is on GitHub.

Avoid unwanted component scanning of Spring Configuration

I came through interesting problem on Stack Overflow. Brett Ryan had problem that Spring Security configuration was initialized twice. When I was looking into his code I spot the problem. Let me show show the code.

He has pretty standard Spring application (not using Spring Boot). Uses more modern Java servlet Configuration based on Spring’s AbstractAnnotationConfigDispatcherServletInitializer.

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends
		AbstractAnnotationConfigDispatcherServletInitializer {


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

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

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

}

As you can see, there are two configuration classes:

  • SecurityConfig – holds Spring Security configuration
  • WebConfig – main Spring’s IoC container configuration
package net.lkrnac.blog.dontscanconfigurations;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("Spring Security init...");
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }

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

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "net.lkrnac.blog.dontscanconfigurations")
public class WebConfig extends WebMvcConfigurerAdapter {

}

Pay attention to the component scanning in WebConfig. It is scanning package where all three classes are located. When you run this on servlet container, text “Spring Security init…” is written to console twice. It mean mean SecurityConfig configuration is loaded twice. It was loaded

  1. During initialization of servlet container in method AppInitializer.getRootConfigClasses()
  2. By component scan in class WebConfig

Why? I found this explanation in Spring’s documentation:

Remember that @Configuration classes are meta-annotated with @Component, so they are candidates for component-scanning!

So this is feature of Spring and therefore we want to avoid component scanning of Spring @Configuration used by Servlet configuration. Brett Ryan independently found this problem and showed his solution in mentioned Stack Overflow question:

@ComponentScan(
    basePackages = "com.acme.app",
    excludeFilters = {
        @Filter(
            type = ASSIGNABLE_TYPE,
            value = { WebConfig.class, SecurityConfig.class }
        )
    })

I don’t like this solution. Annotation is too verbose for me. Also some developer can create new @Configuration class and forget to include it into this filter. I would rather specify special package that would be excluded from Spring’s component scanning.

I created sample project on Github so that you can play with it.

Load implementors of an interface into list with Spring

Last week I wrote a blog post how to load complete inheritance tree of Spring beans into list. Similar feature can be used for autowiring all implementors of certain interface.

Let’s have this structure of Spring beans. Notice that Bear is abstract class, therefore it’s not a Spring bean. So we have three beas: Wolf, PolarBear and Grizzly.

implementors

Now let’s load implementors into list with constructor injection:

@Service
public class Nature {
	List<Runner> runners;

	@Autowired
	public Nature(List<Runner> runners) {
		this.runners = runners;
	}

	public void showRunners() {
		runners.forEach(System.out::println);
	}
}

Method showRunners is using Java 8 forEach method that consumes method reference.  This construct outputs loaded beans into console. You would find a lot of reading about these new Java 8 features these days.

Spring context is loaded by this main class:

public class Main {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext(SpringContext.class);

		Nature nature = context.getBean(Nature.class);
		nature.showRunners();
	}
}

Console output:

PolarBear []
Wolf []
Grizzly []

This feature can be handy sometimes. Source code of this short example is on Github.

Load inheritance tree into List with Spring

I noticed interesting Spring feature. One of my colleagues used it for loading whole inheritance tree of Spring beans into list. Missed that when I was studying Spring docs.

Let’s have this inheritance tree of Spring beans:

animals-class-diagram

Not let’s load inheritance tree of beans into list with constructor injection:

@Component
public class Nature {
	List<Animal> animals;

	@Autowired
	public Nature(List<Animal> animals) {
		this.animals = animals;
	}

	public void showAnimals() {
		animals.forEach(animal -> System.out.println(animal));
	}
}

Method showAnimals is using Java 8 lambda expression to output loaded beans into console. You would find a lot of reading about this new Java 8 feature these days.

Spring context is loaded by this main class:

public class Main {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext(SpringContext.class);

		Nature nature = context.getBean(Nature.class);
		nature.showAnimals();
	}
}

Console output:

PolarBear []
Wolf []
Animal []
Grizzly []
Bear []

This feature can be handy sometimes. Source code of this short example is on Github.

Use Mockito to mock autowired fields

EDIT: Field injections are widely considered (including myself) as bad practice. Read here for more info. I would suggest to use constructor injection instead.

Dependency injection is very powerful feature of Inversion of Control containers like Spring and EJB. It is always good idea to encapsulate injected values into private fields. But encapsulation of autowired fields decreases testability.

I like the way how Mockito solved this problem  to mock autowired fields. Will explain it on example. (This blog post expects that you are little bit familiar with Mockito syntax, but it is self-descriptive enough though.)

Here is first dependency of testing module. It is Spring singleton bean. This class will be mocked in the test.

@Repository
public class OrderDao {
	public Order getOrder(int irderId){
		throw new UnsupportedOperationException("Fail is not mocked!");
	}
}

Here is second dependency of testing class. It is also Spring component. This class will be spied (partially mocked) in test. Its method calculatePriceForOrder will be invoked unchanged. Second method will be stubbed.

@Service
public class PriceService {
	public int getActualPrice(Item item){
		throw new UnsupportedOperationException("Fail is not mocked!");
	}

	public int calculatePriceForOrder(Order order){
		int orderPrice = 0;
		for (Item item : order.getItems()){
			orderPrice += getActualPrice(item);
		}
		return orderPrice;
	}
}

And here is class under test. It  autowires dependencies above.

@Service
public class OrderService {

	@Autowired
	private PriceService priceService;

	@Autowired
	private OrderDao orderDao;

	public int getOrderPrice(int orderId){
		Order order = orderDao.getOrder(orderId);
		return priceService.calculatePriceForOrder(order);
	}
}

Finally here is test example. It uses field level annotations:

  • @InjectMocks – Instantiates testing object instance and tries to inject fields annotated with @Mock or @Spy into private fields of testing object
  • @Mock – Creates mock instance of the field it annotates
  • @Spy – Creates spy for instance of annotated field
public class OrderServiceTest {
	private static final int TEST_ORDER_ID = 15;
	private static final int TEST_SHOES_PRICE = 2;   
	private static final int TEST_SHIRT_PRICE = 1;

	@InjectMocks
	private OrderService testingObject;

	@Spy
	private PriceService priceService;

	@Mock
	private OrderDao orderDao;

	@BeforeMethod
	public void initMocks(){
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void testGetOrderService(){
		Order order = new Order(Arrays.asList(Item.SHOES, Item.SHIRT));
		Mockito.when(orderDao.getOrder(TEST_ORDER_ID)).thenReturn(order);

		//notice different Mockito syntax for spy
		Mockito.doReturn(TEST_SHIRT_PRICE).when(priceService).getActualPrice(Item.SHIRT);
		Mockito.doReturn(TEST_SHOES_PRICE).when(priceService).getActualPrice(Item.SHOES);

		//call testing method
		int actualOrderPrice = testingObject.getOrderPrice(TEST_ORDER_ID);

		Assert.assertEquals(TEST_SHIRT_PRICE + TEST_SHOES_PRICE, actualOrderPrice);
	}
}

So what happen when you run this test:

  1. First of all TestNG framework picks up @BeforeMethod annotation and invokes initMocks method
  2. This method invokes special Mockito call (MockitoAnnotations.initMocks(this)) to initialize annotated fields. Without this call, these objects would be null. Common mistake with this approach is to forget this invocation.
  3. When all the test fields are populated with desired values, test is called.

This example doesn’t include Spring context creation and Spring’s annotations are here only as examples for usage against production code. Test itself doesn’t include  any dependency to Spring and ignores all its annotations. In fact there could be used EJB annotations instead or it can be running against plain (non IoC managed) private fields.

Developers tend to think about MockitoAnnotations.initMocks(this) call as unnecessary overhead. But it is actually very handy, because it resets testing object and re-initializes mocks. You can use it for example

  • When you have various test methods using same annotated instances to ensure that various test runs doesn’t use same recorded behavior
  • When repetitive / parametrized tests are used. For example you can include this call into test  method itself and receive spy object as test parameter (as part of test case). This ability is very sexy in conjunction to TestNG @DataProvider feature (Will explain this in different blog post).

@Spy annotated object can be created in two ways

  • Automatically by Mockito framework if there is default (non-parametrized) constructor
  • Or explicitly initialized (e.g. when there is only non-default constructor)

Testing object annotated by @InjectMocks can be also initialized explicitly.

Example source code can be downloaded from GitHub.