2016-05-23 42 views
0

我遇到組件自動裝配的問題。如何在避免使用null @Autowired的接口實現中自動裝配組件?

我的實現包含在Controller中,Controller使用的接口和實現thagt接口的Component。 我想在實現中自動裝配另一個組件。

這是控制器:

@Controller 
public class MyController { 

    @RequestMapping(path = "/myPath/{subpath}", method = RequestMethod.GET) 
    public void myMethod(@PathVariable("subpath") String subpath, HttpServletResponse response){   
     try{ 
      MyHandler handler = new MyHandlerImpl(response.getOutputStream()); 
      handler.handle();  
     } catch (Exception e) { 

     }  
    } 
} 

這是接口:

public interface MyHandler { 

    public void handle(); 

} 

這是實施:

// tried all: @Component, @Service, @Repository, @Configurable 
public class MyHandlerImpl implements MyHandler { 

    @Autowired 
    MyComponentToAutowired myComponentToAutowired; // <= this is NULL 

    public MyHandlerImpl (ServletOutputStream output) { 
     this.output = output; 
    } 

    private OutputStream output; 

    public void handle() { 
     myComponentToAutowired.theMethod(); // <- NullPointerException at this point 
     // ... 
    } 

    /* 
     If I don't create a default constructor, Spring crash at the start because it not finds the default constructor with no-args. 
    */ 

} 

我能做些什麼,以正確自動裝配組件?

感謝。

+0

創建一個單例MyHandlerImpl bean並將ServletOutputStream傳遞給它的handle句柄。或者在每個請求上創建自己的'MyHandlerImpl'實例,並將'MyComponentToAutowired' bean傳遞給它的'handle'方法。 –

回答

0

您需要使用@Component註釋MyComponentToAutowired實現。你的MyComponentToAutowired實現在哪裏?

這將在Spring上下文中創建一個MyComponentToAutowired實例,該實例將連線到您的MyHandlerImpl實例。

問題是,您正在實例化一個MyHandlerImpl對象,而不是使用由IoC容器(Spring)創建的對象,這是注入了MyComponentToAutowired的對象。

爲了使用有線MyHandlerImpl你應該做

@Component 
public class MyHandlerImpl implements MyHandler { 

@Controller 
public class MyController { 

@Autowired 
MyHandlerImpl myHandler; 

@RequestMapping(path = "/myPath/{subpath}", method = RequestMethod.GET) 
public void myMethod(@PathVariable("subpath") String subpath, HttpServletResponse response){   
    try{ 
     myHandler.setStream(response.getOutputStream()); 
     handler.handle();  
    } catch (Exception e) { 

    }  
    } 
} 

但後來所有的請求都將共享相同的MyHandlerImpl實例,這是你想要什麼沒有。

您可以將MyComponentToAutowired傳遞給句柄方法並將其注入到控制器。

@Controller 
public class MyController { 

@Autowired 
MyComponentToAutowired myComponent; 

@RequestMapping(path = "/myPath/{subpath}", method = RequestMethod.GET) 
public void myMethod(@PathVariable("subpath") String subpath, HttpServletResponse response){   
    try{ 
     MyHandler handler = new MyHandlerImpl(response.getOutputStream()); 
     handler.handle(myComponent);  
    } catch (Exception e) { 

    }  
    } 
} 

我假設你的MyComponentToAutowired是無狀態的。

+0

要自動裝配的組件是@RepositoryRestResource。 –

相關問題