playframework - PlayFramework: 将 spring 依赖注入与PlayFramework集成

  显示原文与译文双语对照的内容

当我尝试在 PlayFramework 中集成 Spring-Dependency-InjectionJava 8 时,我在使用 play clean compile 命令编译代码时得到以下错误


------
value findUserById is not a member of com.harmeetsingh13.controllers.UserController
[error] GET/@com.harmeetsingh13.controllers.UserController.findUserById(userId:Integer)
-------

下面是我的配置和代码


public class GlobalConfiguration extends GlobalSettings{

private AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

@Override
public void onStart(Application app) {
 super.onStart(app);

//AnnotationConfigApplicationContext can only be refreshed once, but we do it here even though this method
//can be called multiple times. The reason for doing during startup is so that the Play configuration is
//entirely available to this application context.
 applicationContext.scan("com.harmeetsingh13");
 applicationContext.refresh();

//This will construct the beans and call any construction lifecycle methods e.g. @PostConstruct
 applicationContext.start();
}

@Override
public void onStop(Application app) {
//This will call any destruction lifecycle methods and then release the beans e.g. @PreDestroy
 applicationContext.close();

 super.onStop(app);
}

@Override
public <A> A getControllerInstance(Class<A> clazz) throws Exception {
 return applicationContext.getBean(clazz);
}
}

我的Coltroller:


@Named
@Singleton
public class UserController extends Controller{


public static Result findUserById(Integer userId) {
/*Optional<User> user = userService.findUserById(userId);
 if(user.isPresent()){

 }*/
 return null;
}
}

我的路由文件如下:


Routes

# Home page
GET/@com.harmeetsingh13.controllers.UserController.findUserById(userId:Integer)

时间: 原作者:

最后我找到并回答了,当我们使用 Play Framework的依赖注入时,无需将控制器方法声明为 static 。 从控制器方法中删除 static 关键字。 这是因为,对象是以bean的形式处理的,IOC容器创建控制器 bean,Play Framework 从bean获取方法定义。 这就是为什么在控制器中不需要 static 方法的原因。


public Result findUserById(Integer userId) {
 -------
return null;
}

原作者:
...