在Play Framework中放置服务类的位置?

时间:2011-06-09 21:03:26

标签: playframework

在Grails中,我们有服务类,其中包含从控制器调用的业务逻辑。 我在哪里将服务类放在Play Framework项目中?如果我在控制器中定义了不是请求操作的方法,而在控制器中定义了诸如int findMax(int a,int b)之类的实用方法,那么这可以在控制器中定义吗?如何声明这样的方法?

3 个答案:

答案 0 :(得分:8)

一般而言,业务逻辑应该作为模型类的方法实现,无论是静态还是非静态,具体取决于上下文。

虽然没有关于此的规则,但实用程序方法应该放在包中的自己的实用程序类中,或者根据上下文可以成为模型类的一部分。

作为示例,比较两个基元(例如findMax(int, int)类)的简单实用程序方法在实用程序类中更好,但findOldest(Person, Person)之类的方法更适合作为Person模型类上的静态方法。

答案 1 :(得分:2)

这没有规则。我个人会将实用程序方法放在实用程序类中。实用程序类和服务类应遵循常规的包规则,即com.stackoverflow.services.statistic.UsageCalculator

答案 2 :(得分:0)

您可以在app文件夹中创建包并编写自己的Service类或逻辑类。 在Application controller中使用这个新创建的Service / logic类及其方法。

在app文件夹中创建包: 例如。 play.service.chiken并在此包中创建新类

package play.service.chiken;

import java.util.ArrayList;
import java.util.List;

import models.QuotesModel;

public class Utility {


public List<QuotesModel> getListOfQuotes(int itemCount) {
    ArrayList<QuotesModel> list=new ArrayList<QuotesModel>(10);
        for(int x=0;x<itemCount;x++) {
            QuotesModel quotesModel=new QuotesModel();
            quotesModel.authorName="";
            quotesModel.category="";
            quotesModel.bookmark="Y";
            quotesModel.id=x+"";
            quotesModel.content="Quotes n umber ,njdsfkhwjd jr x=" +x;
            list.add(quotesModel);
        }
        return list;
    }
}

然后在Application Controller中使用此类:

public static Result entryInDB() {
    Utility util=new Utility();
    List<QuotesModel> list=util.getListOfQuotes(50);

    list.get(2).save();

    List<QuotesModel>  secondlist=QuotesModel.find.all();

    return ok(index.render("Size Of List "+secondlist.toString()));
}

conf / application.conf文件中的更改:

# Ebean configuration
      # ~~~~~
      # You can declare as many Ebean servers as you want.
      # By convention, the default server is named `default`
      #
      ebean.default="models.*"

在Routes文件中:

# Home page
    GET     /                   controllers.Application.index()
    GET     /addbar             controllers.Application.addBar()
    GET     /entryindb          controllers.Application.entryInDB()