简体   繁体   中英

How to inject dependency in Servlet in Spring MVC 4?

At present in my spring mvc based application i am implementing Servlets as well (this is a healthcheck servlet). I am trying to inject dependency of a class in this servlet using @Autowire annotation but this class is not instantiating.

Please consider the below code.

@WebServlet(name = "myServlet", urlPatterns = "/app2")
public class HealthCheckController extends HealthCheckServlet{

/** The Constant serialVersionUID. */

    private static final long serialVersionUID = 1L;

    @Autowire
      private MyService service;

    /**
     * method to check healthiness.
     *
     * @return true, if is healthy
     * @throws HealthCheckException the health check exception
     */
    @Override
    public boolean isHealthy() throws HealthCheckException {
        try {
            service.showDetails("12", false,null);
            System.out.println("True");
            return true;
        } catch (Exception  e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

Could you please suggest how can i provide dependency of MyService class?

Thanks in advance.

This is not a Spring managed bean. Try adding @Component to the class declaration.

@Component
@WebServlet(name = "myServlet", urlPatterns = "/app2")
public class HealthCheckController extends HealthCheckServlet{

You can also try to refactor your class to be a Spring Controller:

@Controller
@RequestMapping("app2")
public class HealthCheckController extends HealthCheckServlet{

Another thing you can try is adding the servlet in the web.xml instead of using the @WebServlet annotation.

<servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>mypackage.HealthCheckController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>/app2</url-pattern>
</servlet-mapping>

Add '@Controller' as mentioned in the comments and update your URL mapping. Also, what is calling isHealthy()? Try adding your url mapping there.

@Controller
public class HealthCheckController extends HealthCheckServlet{

private static final long serialVersionUID = 1L;

@Autowire
  private MyService service;

@RequestMapping("/app2/*")
public boolean isHealthy() throws HealthCheckException {
    try {
        service.showDetails("12", false,null);
        System.out.println("True");
        return true;
    } catch (Exception  e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM