Implement Spring Actuator in my Spring MVC app wit

2019-09-24 05:19发布

问题:

Currently I have a legacy project that uses spring MVC. Now there is need to implement Spring boot actuator. So my questions are

  1. Can I implement Spring Actuator in my Spring MVC app without adding Spring boot
  2. Can I have both Spring boot and spring MVC in one single application. If Yes then how.

It would be great if someone can describe step by step implementation of it. I am using Eclipse, Gradle, Tomcat

回答1:

To answer your first question:

  1. yes You can use actuator in your spring mvc project. Add this to pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-actuator</artifactId>
        <version>Compatible version with mvc</version>
    </dependency>
    
  2. Add configuration below

    @Configuration
    @EnableWebMvc
    @Import({EndpointAutoConfiguration.class , PublicMetricsAutoConfiguration.class , HealthIndicatorAutoConfiguration.class
    })
    public class MyActuatorConfig {
    
        @Bean
        @Autowired
        public EndpointHandlerMapping endpointHandlerMapping(Collection<? extends MvcEndpoint> endpoints) {
          return new EndpointHandlerMapping(endpoints);
        }
    
       @Bean
       @Autowired
       public EndpointMvcAdapter metricsEndPoint(MetricsEndpoint delegate) {
          return new EndpointMvcAdapter(delegate);
      }
    }
    

2. Answer your second questions

Of course you can use Spring boot and spring MVC, just simple have below as parent to manage all dependencies version etc..

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

and spring-boot-starter-web as dependency.

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>