简体   繁体   中英

PlayFramework: Integrate Spring Dependency Injection With PlayFramework

When i try to integrate Spring-Dependency-Injection in PlayFramework with Java 8 , I get the following error when compile the code using play clean compile command

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

Following is my Configuration and code

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

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

My Route File as follow:

Routes

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

At last i found and answer, When we used Dependency injection with Play Framework there no need to declare controller method as a static. Just remove the static keyword from controller method. This is because, the objects are deal in the form of bean, the IOC container create the controller bean and Play Framework get the method definition from bean. That's why there is no need to static methods in controller.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM