Spring Boot - apycazo/playground GitHub Wiki

Annotations

Validation using a pattern (configprops)

@NotNull
@Pattern(regexp = "\\w+", message = "ID must only contains letters, numbers and '_'")
private String id;

Json order & ignore

@JsonPropertyOrder({ "id", "firstname", "lastname" })
@JsonInclude(Include.NON_EMPTY)
public class User {
    private Long id;
    private String firstname;
    private String lastname;
}

Add a resource path handler

@Configuration
@EnableWebMvc
public class WebResourceConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/static/**/*")                
                .addResourceLocations(
                        "/resources/static/test",
                        "/resources/static/common"
                );
    }
}

Include property info on META-INF

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
</dependency>

Run method after context loads

@Slf4j
@Component
public class AfterContextLoads implements ApplicationListener<ContextRefreshedEvent> {
    
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event)
    {
        log.info("--- READY ---");
        // just so a report can be logger after startup.
    }
}

Test URL after servlet loads

@Slf4j
@Component
public class SetupTest implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
    
    @Autowired
    private ServletContext servletContext;
    
    @Override
    public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event)
    {
        // Base url
        String base = "http://127.0.0.1";
        int port = event.getEmbeddedServletContainer().getPort();
        String contextPath = servletContext.getContextPath();
        String url = base + ":" + port + contextPath + "/echo-test";
        
        RestTemplate rest = new RestTemplate();
        try {            
            URI uri = new URI(url);
            ResponseEntity<String> response = rest.getForEntity(uri, String.class);
            log.info("Echo test on {}", uri.toString());
            log.info("Check response... {}", (response == null ? "KO" : "OK"));
            if (response != null) {
                log.info("Check status...   {}", 
                        (response.getStatusCode() != HttpStatus.OK ? "KO" : "OK"));
                log.info("Check body...     {}", 
                        (response.getBody() == null || response.getBody().isEmpty() ? "KO" : "OK"));
            }
        } catch (URISyntaxException | RestClientException e) {
            log.warn("Unable to generate test query url {}", url, e);
        }
    }
}

Spring Boot Unit test starter

// To be replaced with the correct BootStrap class
import com.alcatellucent.chameleon.thirdparties.vast.bs.BootStrap;
import com.jayway.restassured.RestAssured;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/**
 * Base class with the server initialization methods.
 *
 * @author Andres Picazo
 */
@Slf4j
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {BootStrap.class})
@IntegrationTest("server.port:0")
@EnableAutoConfiguration
public class ServerInitializerHelper {
    
    @Value("${local.server.port}")
    private int port;
    protected final String NAME = "TEST-SERVER";
    protected final Marker marker = MarkerFactory.getMarker(NAME);
    protected String baseURL;
 
    protected void trace(String format, Object... elems)
    {
        if (elems != null && elems.length > 0) {
            log.debug(marker, format, elems);
        } else {
            log.debug(marker, format);
        }
    }
 
    @Before
    public void setup()
    {
        trace("Test server started on port {}", port);
        RestAssured.port = port;
        // Replace props with mocked URL
        baseURL = "http://127.0.0.1:" + port;
    }
 
    public String getURL() { return baseURL; }
  
    public String getPath (String relativePath) 
    {
        if (relativePath.endsWith("/")) {
            relativePath = relativePath.substring(0, relativePath.length()-1);
        }
        if (relativePath.startsWith("/")) {
            return baseURL + relativePath;
        }
        else {
            return baseURL + "/" + relativePath;
        }
    }
}

Add properties without an annotation

@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
    PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();
    propertyConfigurer.setLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/**/abc.properties"));
    return propertyConfigurer;
}

Map a property list or array

@Component
@ConfigurationProperties(prefix = "test")
public class PropTest {
    
    protected String [] locators = new String[0];    
 
    @PostConstruct
    protected void _init()
    {
        for (String s : locators) {
            System.out.println("Found locator " + s);
        }
    }
}

application.properties

test.locator : first,second
⚠️ **GitHub.com Fallback** ⚠️