Chinese Services

服务

Grails服务(Grails Services)

服务是指实现了业务逻辑的类。A service is a class that holds one or more methods that implement business logic. Logical parts of the business logic are contained in seperate service classes. 服务类按事务进行分开,以便每个方法可以在持久层保持原子性,当某种类型的异常被抛出后,事务可以被回滚。

Services need to be registered with the middle tier and also need transactional configuration next to the configuration of optional AOP services.

服务类的可是范围是整个应用层(application-scoped),不应该用于实例变量(instance variables),因为可能会在同一时间进行并发修改。

服务类的代码约定

服务类的类名必须以服务的名字开头,结尾为"Service"."国家"的服务类可以叫"CountryService"。

默认情况下,所有服务类中的事务都是开启的。可通过设置属性"transactional"为false来禁止事务。如:

class CountryService {
    boolean transactional = false
}

依赖注入(Dependency Injection)

可以通过设置相应的属性来注入其他服务类。如要注射CountrySerice要通过设置属性"countryService"。

CountryService countryService

通过添加一个属性能够获得一个数据库的javax.sql.DataSource实例

javax.sql.DataSource dataSource

这可以与 Spring's JdbcTemplate 或者 Groovy Sql 一起使用来直接执行事务性 SQL 操作。

访问服务

在一个典型的多层应用中,你可以使用依赖注入很容易的访问服务,比如在一个controller中:

class CountryService {
    def String sayHello(String name) {
        return "hello ${name}"
    }
}

class GreetingController {
    CountryService countryService
    def helloAction = {
        render(countryService.sayHello(params.name))
    }
}

 现在,你可以通过在浏览器地址栏输入 http://myserver:8080/myapp/greeting/helloAction?name=Falken来测试它。浏览器将会显示一个包含 "hello Falken" 的页面。 关于controller的详细介绍参见 Grails controllers

Alternatively, you can access services from other places of your web application (like servlets) if you need it. Service objects are beans which can be retrieved from the Spring Bean Factory. You can proceed this way:

Implement a java interface containing the service method definitions which you want to be available, for example:

package serviceinterfaces;

public interface CountryServiceInt {
    public String sayHello(String name);
}

Save it in your  "<..>/myapp/src/java/serviceinterfaces" directory

Modify the CountryService groovy class for implementing the CountryServiceInt interface:

class CountryService implements serviceinterfaces.CountryServiceInt {

    def String sayHello(String name) {
        return "hello ${name}"
    }
}

For accessing the service from a servlet you can do this:

ApplicationContext ctx = (ApplicationContext) request.getSession().getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
CountryServiceInt service = (CountryServiceInt) ctx.getBean("countryService");
String str = service.sayHello(request.getParameter.("name"));
//do something with str
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.