教程 > spring boot 中文教程 >
阅读:67
spring boot service 组件——迹忆客-ag捕鱼王app官网
服务(service)组件是包含 @service
注解的类文件。 这些类文件用于在不同的层中编写业务逻辑,与 @restcontroller
类文件分开。创建服务组件类文件的逻辑如下所示
public interface productservice {
}
实现带有@service注解的接口的类如下
@service
public class productserviceimpl implements productservice {
}
请注意,在本教程中,我们使用 product 服务 api 来存储、检索、更新和删除商品。 我们在 @restcontroller
类文件本身中编写了业务逻辑。 现在,我们要将业务逻辑代码从控制器移动到服务组件。
我们可以使用如下所示的代码创建一个包含添加、编辑、获取和删除方法的接口
package com.study.service;
import com.study.model.product;
import java.util.collection;
/**
* @author jiyik.com
*/
public interface productservice {
public abstract void createproduct(product product);
public abstract void updateproduct(string id, product product);
public abstract void deleteproduct(string id);
public abstract collection getproducts();
}
我们将使用以下代码创建一个类,该类使用 @service
注解实现 productservice
接口,并编写业务逻辑来存储、检索、删除和更新商品。
package com.study.service;
import com.study.model.product;
import java.util.collection;
import java.util.hashmap;
import java.util.map;
/**
* @author jiyik.com
*/
public class productserviceimpl implements productservice {
private static map productrepo = new hashmap<>();
static {
product honey = new product();
honey.setid("1");
honey.setname("honey");
productrepo.put(honey.getid(), honey);
product almond = new product();
almond.setid("2");
almond.setname("almond");
productrepo.put(almond.getid(), almond);
}
@override
public void createproduct(product product) {
productrepo.put(product.getid(), product);
}
@override
public void updateproduct(string id, product product) {
productrepo.remove(id);
product.setid(id);
productrepo.put(id, product);
}
@override
public void deleteproduct(string id) {
productrepo.remove(id);
}
@override
public collection getproducts() {
return productrepo.values();
}
}
下面的代码显示了 rest controller 类文件,这里我们 @autowired
了 productservice 接口并调用了方法。
package com.study.controller;
import com.study.service.productservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.restcontroller;
import com.study.model.product;
@restcontroller
public class productservicecontroller {
@autowired
productservice productservice;
@requestmapping(value = "/products/{id}", method = requestmethod.put)
public responseentity