我正在尝试制作图片上传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);
}
}
其他信息:
pom.xml
为spring-aspects
添加了依赖项
spring-instrument
我在NullPointerException
收到了ImageUploadTask
。我怀疑@Autowired
没有按预期工作。
@Autowired
时才必须使用@Conigurable
,为什么不使用@Inject
? (虽然我尝试过并获得相同的NPE)答案 0 :(得分:1)
默认情况下,@Configurable
的自动装配是关闭,即Autowire.NO,imageUploadService
为null
因此更新代码以明确地将其启用为BY_NAME或BY_TYPE,如下所示。
@Component
@Configurable(preConstruction = true, autowire = Autowire.BY_NAME)
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ImageUploadTask implements Callable<JSONObject> { .... }
其余配置即。启用加载时间编织似乎很好。
同样关于@Inject
注释的外观here几乎可以解释差异(或相似度)