Skip to content

Instantly share code, notes, and snippets.

@arvindkgs
Last active March 6, 2023 06:51
Show Gist options
  • Save arvindkgs/385f7859aff7d67086ed0af5c2f25bee to your computer and use it in GitHub Desktop.
Save arvindkgs/385f7859aff7d67086ed0af5c2f25bee to your computer and use it in GitHub Desktop.
[Spring Debug] Spring Debug

Print all beans on startup

@SpringBootApplication
public class Application {

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

  @Bean
  public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

      System.out.println("Let's inspect the beans provided by Spring Boot:");

      String[] beanNames = ctx.getBeanDefinitionNames();
      Arrays.sort(beanNames);
      for (String beanName : beanNames) {
        System.out.println(beanName);
      }
    };
  }    
}

Print all properties from application.properties/yaml and from environment

 package com.nile.billing.components;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AppContextEventListener {

    @EventListener
    public void handleContextRefreshed(ContextRefreshedEvent event) {
        printActiveProperties(
                (ConfigurableEnvironment) event.getApplicationContext().getEnvironment());
    }

    private void printActiveProperties(ConfigurableEnvironment env) {

        System.out.println(
                "************************* ACTIVE APP PROPERTIES ******************************");

        List<MapPropertySource> propertySources = new ArrayList<>();

        env.getPropertySources()
                .forEach(
                        it -> {
                            if (it instanceof MapPropertySource
                                    && it.getName().contains("applicationConfig")) {
                                propertySources.add((MapPropertySource) it);
                            }
                        });

        propertySources.stream()
                .map(propertySource -> propertySource.getSource().keySet())
                .flatMap(Collection::stream)
                .distinct()
                .sorted()
                .forEach(
                        key -> {
                            try {
                                System.out.println(key + "=" + env.getProperty(key));
                            } catch (Exception e) {
                                log.warn("{} -> {}", key, e.getMessage());
                            }
                        });
        System.out.println(
                "******************************************************************************");
    }
}

Print exposed REST paths

@Component
public class EndpointsListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods()
                .forEach((x, y) -> System.out.println(x.getDirectPaths()));
    }
}

Enable hibernate full SQL script

Print sql statement

spring.jpa.properties.hibernate.format_sql=true spring.jpa.show_sql=true logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

To switch off logs during unit-tests (including hibernate logs)

logging.level.root=OFF logging.level.org.springframework.boot=OFF logging.level.org.springframework=OFF logging.level.org.hibernate=OFF logging.level.org.hibernate.SQL=INFO logging.level.org.hibernate.type=OFF spring.main.banner-mode=OFF spring.jpa.show-sql=false spring.jpa.properties.hibernate.show_sql=false

Maven

Spring system args

  1. -Dspring-boot.run.jvmArguments="-D=value".
    Example: -Dspring-boot.run.jvmArguments="-Dspring.config.location=charts/audit/config-develop.yaml"

Jar

Spring system args

  1. --=value
    Example: --spring.config.location=charts/tenantservice/config-develop.yaml

Using environment variables

  1. export SPRING_CONFIG_LOCATION=charts/tenantservice/config-develop.yaml, spring will pickup that as spring.config.location

@WebMvcTest - for testing the controller layer @JsonTest - for testing the JSON marshalling and unmarshalling @DataJpaTest - for testing the repository layer @RestClientTests - for testing REST clients @SpringBootTest - for starting whole springboot app

JPA Entities and repositories can be tested through @DataJpaTest.

Example:

@RunWith(SpringRunner.class)
@AutoConfigureTestEntityManager
@DataJpaTest
public class JpaTest {
	@Autowired
    TestEntityManager testEntityManager;
    
    @Autowired
    JpaRepository repo;
    
    @Test
    public void testRepo() {
    	Entity e = new Entity();
        // e.setData
    	testEntityManager.persistAndFlush(e);
        testEntityManager.clear()
        // remember to flush and clear, after persisting
        Entity actual = repo.findById(e.getId());
        Assert.assertEquals(e, actual);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment