官术网_书友最值得收藏!

  • Spring 5.0 By Example
  • Claudio Eduardo de Oliveira
  • 266字
  • 2021-06-24 19:17:36

CategoryService

Let's start with our simplest service, the CategoryService class, the behaviors expected of this class are CRUD operations. Then, we need a representation of our persistence storage or repository implementation, for now, we are using the ephemeral storage and ArrayList with our categories. In the next chapter, we will add the real persistence for our CMS application.

Let's create our first Spring service. The implementation is in the following snippet:

package springfive.cms.domain.service;

import java.util.List;
import org.springframework.stereotype.Service;
import springfive.cms.domain.models.Category;
import springfive.cms.domain.repository.CategoryRepository;

@Service
public class CategoryService {

private final CategoryRepository categoryRepository;

public CategoryService(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
}

public Category update(Category category){
return this.categoryRepository.save(category);
}

public Category create(Category category){
return this.categoryRepository.save(category);
}

public void delete(String id){
final Category category = this.categoryRepository.findOne(id);
this.categoryRepository.delete(category);
}

public List<Category> findAll(){
return this.categoryRepository.findAll();
}

public Category findOne(String id){
return this.categoryRepository.findOne(id);
}

}

There is some new stuff here. This class will be detected and instantiated by the Spring container because it has a @Service annotation. As we can see, there is nothing special in that class. It does not necessarily extend any class or implement an interface. We received the CategoryRepository on a constructor, this class will be provided by the Spring container because we instruct the container to produce this, but in Spring 5 it is not necessary to use @Autowired anymore in the constructor. It works because we had the only one constructor in that class and Spring will detect it. Also, we have a couple of methods which represent the CRUD behaviors, and it is simple to understand.

主站蜘蛛池模板: 汶上县| 手机| 黔西| 徐汇区| 石家庄市| 札达县| 南昌市| 浪卡子县| 二连浩特市| 姚安县| 忻州市| 罗山县| 大宁县| 东台市| 黄浦区| 获嘉县| 永福县| 姚安县| 贵阳市| 永登县| 宁城县| 东乌珠穆沁旗| 潞西市| 沁阳市| 新巴尔虎左旗| 辽阳县| 伊宁市| 丰城市| 双鸭山市| 龙川县| 营口市| 赞皇县| 唐海县| 平利县| 昭通市| 稻城县| 白沙| 乌鲁木齐县| 朝阳市| 琼结县| 南昌县|