This is a glossary of all the common issues in Spring projects Spring Boot
  • 27-Dec-2022
Lightrun Team
Author Lightrun Team
Share
This is a glossary of all the common issues in Spring projects Spring Boot

Troubleshooting Common Issues in Spring Projects. Spring Boot

Lightrun Team
Lightrun Team
27-Dec-2022

Project Description

 

Spring Boot is a Java-based framework used to create stand-alone, production-grade applications. It is built on top of the Spring Framework, which is a popular framework for building Java applications, and it takes advantage of many of the features that the Spring Framework provides.

One of the key features of Spring Boot is its ability to automatically configure a Spring application based on the dependencies that are present on the classpath. For example, if you include the Spring Data JPA library on the classpath, Spring Boot will automatically configure a data source and set up the necessary infrastructure to connect to a database.

Spring Boot also provides a number of useful tools and features to make it easier to develop and deploy Java applications. For example, it includes an embedded web server, which can be used to run the application in a development environment, and it also provides a number of plugins for popular build tools, such as Maven and Gradle, to make it easy to build and deploy applications.

Overall, Spring Boot is a powerful tool for building and deploying Java applications, and it is especially useful for developing microservices and other types of applications that are designed to be run in a cloud environment.

 

Troubleshooting Spring Projects-Spring Boot with the Lightrun Developer Observability Platform

 

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.
  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

The most common issues for Spring Projects-Spring Boot are:

 

Support .env file for configuration properties

 

At Spring Boot, we recognize the potential of exploiting .env files as a way of optimizing user experience. To ensure our implementation meets this goal, we have marked an issue for pending design work to further discuss and select from multiple options. These include; automatically processing dot-env format-based configuration within current directories and introducing new ConfigDataLocationResolver & Loader features to interpret environment variables instead of properties via “spring.config.” directives Moreover, support is also being considered towards developing hint types related to extensionless files containing variable key-pairs through similar commands such as “spring.config”.

 

Make @ConfigurationProperties available in conditions

 

Using matchIfMissing as a workaround to resolve cases of this nature is certainly an option; however, it isn’t the most elegant approach. It requires that we replicate values for @ConfigurationProperty such as bar = true – and if those default settings are ever adjusted in the future, necessary modifications must also be applied accordingly within any associated beans/configs. This solution can only accommodate booleans too – String-based defaults simply won’t suffice here.

  @ConditionalOnProperty(prefix="foo", name="bar", havingValue="defaultStringValue")

 

Allow provided and optional dependencies to be excluded when building a fat jar with Maven

 

Configuration exclusion appears to be an efficient solution, however, it may not fulfill all of the necessary criteria.

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                  <excludes>
                    <exclude>
                      <groupId>org.projectlombok</groupId>
                      <artifactId>lombok</artifactId>
                    </exclude>
                  </excludes>
                </configuration>
            </plugin>

 

Ability to customize log file name when logging.path is set

 

With the help of logging.file.name, a user can designate both an exact pathway and filename for their ticket to be logged in – no longer requiring any other documentation! As an example:

/logs/${spring.application.name}.log

 

Support java.nio.file Paths and FileSystems with fat jars

 

By prefixing the path with BOOT-INF/classes, it is possible to effectively bypass this issue and achieve a successful resolution.

  String resourceDirectory = "/my/resource/dir";
  URI uri = getClass().getResource(resourceDirectory).toURI();
  Path path;

  if (uri.getScheme().equals("jar")) {
    FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap());
    path = fileSystem.getPath("/BOOT-INF/classes" + resourceDirectory);
  } else {
    // Not running in a jar, so just use a regular filesystem path
    path = Paths.get(uri);
  }

  Files.walk(path).forEach(...);

Although a workable solution, it is less than ideal to have a code directly dependent on an implementation detail of Spring Boot’s executable jar architecture.

 

Suppress “Circular view path [error]” error message

 

The situation occurs when spring-boot 1.5.19 is used in conjunction with the embedded tomcat container, whereupon upon receiving a RuntimeException from the controller on the server side, Tomcat will generate its standard error page for settings without white labeling enabled; however, this action results in logging unpleasant errors internally as well.

javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. 
Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

This perplexing error has left many scratching their heads, especially considering that the official documents from Spring Boot (https://docs.spring.io/ spring-boot/docs /1 .5 .19.RELEASE/reference/html//howto-actuator html) appear to be accurate in their assertion of what should have taken place.

Set server.error.whitelabel.enabled=false to switch the default error page off which will restore the default of the servlet container that you are using. Note that Spring Boot will still attempt to resolve the error view so you’d probably add you own error page rather than disabling it completely.

ErrorPageCustomizer within ErrorMvcAutoConfiguration is the force behind registering an Error Page, even when server.error.whitelabel.enabled has been disabled.

The assessment is that appending the ErrorPage should not be set as a standard measure, but rather remain an optional procedure. Combining two autoconfiguration mechanisms can consequently result in generating confounding errors and logs.

To maintain backward compatibility, a property (server.error.register-default-error page) is enabled by default; however, it can be toggled off if required.

Through a quick validation of the bean name “error”, it can be determined whether WhitelabelErrorViewConfiguration has been handled or if you have defined your own error view.

Ensure an optimal user experience – ErrorPageCustomizer can be enabled via @ConditionalOnMissingBean to customize your own empty implementation.

To achieve the desired outcome, utilize a BeanPostProcessor with less-than-ideal results in Spring Boot 2 code.

@Component
public class RemoveErrorPages implements BeanPostProcessor, EnvironmentAware {
    private Environment environment;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if( bean instanceof AbstractConfigurableWebServerFactory) {
            if( "false".equals( environment.getProperty("server.error.whitelabel.enabled") ) ) {
                ((AbstractConfigurableWebServerFactory) bean).getErrorPages().clear();
            }
        }
        return bean;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}

Of course, using

spring:
  autoconfigure:
    exclude: 'org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration'

The quandary of an apparent error message in Spring Boot 2.1.3 RELEASE persists, meaning a proper resolution is still required for this discrepancy. All possible adjustments to configuration carry the potential for merely working around the issue without actually addressing it.

 

Add JUnit 5 parameter resolver for @MockBean

 

Constructor parameters have a specific use and purpose, one that is vital to the proper functioning of your code..

@ExtendWith(SpringExtension::class)
@WebMvcTest
class HttpApiTests(@Autowired val mockMvc: MockMvc) {

	@MockBean
	private lateinit var userRepository: UserRepository

	@Test
	fun foo() { }
}

Versus

@ExtendWith(SpringExtension::class)
@WebMvcTest
class HttpApiTests(@Autowired val mockMvc: MockMvc,
                   @MockBean val userRepository: UserRepository) {

	@Test
	fun foo() { }
}

 

Support @MockBean on test fields with TestNG

 

 

After making alterations to WebMockTest in the realm of Testing the Web Layer a successful result can be achieved.

@WebMvcTest(GreetingController.class)
@TestExecutionListeners(MockitoTestExecutionListener.class)
@Test
public class WebMockTestNg extends AbstractTestNGSpringContextTests {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private GreetingService service;

    @Test
    public void greetingShouldReturnMessageFromService() throws Exception {
        when(service.greet()).thenReturn("Hello Mock");
        this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString("Hello Mock")));
    }
}

or like below:

@SpringBootTest(classes = GreetingController.class)
@AutoConfigureWebMvc
@AutoConfigureMockMvc
@TestExecutionListeners(MockitoTestExecutionListener.class)
public class WebMockTestNg extends AbstractTestNGSpringContextTests {
  // ...
}

To ensure the successful execution of your test code, adding @TestExecutionListeners(MockitoTestExecutionListener.class) is essential.

 

More issues from Spring Projects repos

 

Troubleshooting spring-projects-spring-framework | Troubleshooting-spring-projects-spring-data-jpa | Troubleshooting-spring-projects-spring-data-rest | Troubleshooting-spring-projects-spring-security

 

 

 

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.