@Autowired不适用于@Configurable

时间:2016-12-07 03:29:12

标签: spring spring-boot dependency-injection nullpointerexception autowired

我正在尝试制作图片上传API。我有一个ImageUpload任务,如下所示,

@Component
@Configurable(preConstruction = true)
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ImageUploadTask implements Callable<JSONObject> {

 @Autowired
 private ImageUploadService imageUploadService;

 @Override
 public JSONObject call() throws Exception {
    .... 
    //Upload image via `imageUploadService`
   imageUploadService.getService().path('...').post('...'); // Getting null pointer here for imageUploadService which is a WebTarget

 }
}

ImageUploadService如下所示,

@Component
public class ImageUploadService {

@Inject
@EndPoint(name="imageservice") //Custom annotation, battle tested and works well for all other services
private WebTarget imageservice;

public WebTarget getService() {
    return imageservice;
 }
}

这是spring boot应用程序类,

@ComponentScan
@EnableSpringConfigured
@EnableLoadTimeWeaving(aspectjWeaving=EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
@EnableAutoConfiguration
public class ImageApplication extends SpringBootServletInitializer {

 @Bean
 public InstrumentationLoadTimeWeaver loadTimeWeaver() throws Throwable   {
    InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
    return loadTimeWeaver;
 }

 @Override
 public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);
    servletContext.addListener(new RequestContextListener());
 }

 public static void main(String[] args) throws IOException {
    SpringApplication.run(ImageApplication.class);
 }
}

其他信息:

  • 依赖项的Spring版本位于4.2.5.RELEASE
  • pom.xmlspring-aspects添加了依赖项 spring-instrument

我在NullPointerException收到了ImageUploadTask。我怀疑@Autowired没有按预期工作。

  • 为什么不起作用,我该如何解决这个问题?
  • 仅在我使用@Autowired时才必须使用@Conigurable,为什么不使用@Inject? (虽然我尝试过并获得相同的NPE)

1 个答案:

答案 0 :(得分:1)

默认情况下,@Configurable的自动装配是关闭,即Autowire.NOimageUploadServicenull

因此更新代码以明确地将其启用为BY_NAMEBY_TYPE,如下所示。

@Component
@Configurable(preConstruction = true, autowire = Autowire.BY_NAME)
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ImageUploadTask implements Callable<JSONObject> { .... }

其余配置即。启用加载时间编织似乎很好。

同样关于@Inject注释的外观here几乎可以解释差异(或相似度