1

I am trying to do an image upload API. I have a ImageUpload task as follows,

@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

 }
}

The ImageUploadService looks like the below,

@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;
 }
}

Here is the spring boot application class,

@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);
 }
}

Additional information :

  • Spring version of dependencies are at 4.2.5.RELEASE
  • pom.xml has dependencies added for spring-aspects and spring-instrument

I am getting a NullPointerException in ImageUploadTask. My suspicion is that @Autowired doesn't work as expected.

  • Why wouldn't work and how do I fix this?
  • Is it mandatory to use @Autowired only when I use @Conigurable, why not use @Inject? (though I tried it and getting same NPE)
g0c00l.g33k
  • 2,458
  • 2
  • 31
  • 41

1 Answers1

1

By default the autowiring for the @Configurable is off i.e. Autowire.NO beacuse of which the imageUploadService is null

Thus update the code to explicity enable it either as BY_NAME or BY_TYPE as below.

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

Rest of the configuration viz. enabling load time weaving seems fine.

Also regarding @Inject annotation have a look here which pretty much explains the difference (or similarity perhaps)

Community
  • 1
  • 1
Bond - Java Bond
  • 3,972
  • 6
  • 36
  • 59