2017-07-13 65 views
1

我剛剛開始使用DI和Spring。我有這兩種成分(僞)帶註釋的spring depenency注入

@Component 
public class AuthHandlerImpl extends ChannelInboundHandlerAdapter implements AuthHandler { 

    @Autowired 
    AuthService authService; 

    @Override 
    channelRead(ChannelHandlerContext ctx, Object msg) { 
     authService.authenticate(msg); // want to pass ctx to constructor of authService 
    } 
} 

@Component 
public class AuthServiceImpl implements AuthService { 

    private CustomerService customerService; 

    private ChannelHandlerContext ctx; 

    @Autowired 
    public AuthServiceImpl(CustomerService customerService, ChannelHandlerContext ctx) { 
     this.customerService = customerService; 
     this.ctx = ctx; 
    } 
} 

我試圖做到的,是有AuthService注射構造函數的參數,其中的構造函數的參數之一是ChannelHandlerContext從ChannelInboundHandlerAdapter類。不知道這是否可能。

回答

1

是的,這是可能的,但CustomerService和ChannerHandlerContext必須定義爲spring bean(如@Component,@Service,@Controller或@Bean註釋)以在構造函數中自動裝配。您可以查看this的帖子以獲得更多關於該主題的信息。

+0

所以如果ChannelHandlerContext是第三方框架類型,那還有可能嗎?有沒有可能與註釋? – Crystal

+1

您可以定義一個\ @Configuration類。在內部,您需要創建一個具有特定註釋(\ @Bean)的方法,該方法負責返回您的第三方組件。 \ @Configuration 類MyConfigurationClass { \ @Bean 公共getChannelHandlerContext(){ 返回新ChannelHandlerConext(); //現在,通過\ @Bean註釋,ChannelHandlerContext是一個spring bean。 } } –