Open conchincradle opened 2 years ago
public interface PostService { PostDto createPost(PostDto postDto); }
@Service
public class PostServiceImpl implements PostService {
private PostRepository postRepository;
//@Autowired
public PostServiceImpl(PostRepository postRepository) {
this.postRepository = postRepository;
}
@Override
public PostDto createPost(PostDto postDto) {
// convert DTO to entity
Post post = new Post();
post.setTitle(postDto.getTitle());
post.setDescription(postDto.getDescription());
post.setContent(postDto.getContent());
Post newPost = postRepository.save(post);
// convert entity to DTO
PostDto postResponse = new PostDto();
postResponse.setId(newPost.getId());
postResponse.setContent(newPost.getContent());
postResponse.setDescription(newPost.getDescription());
postResponse.setTitle(newPost.getTitle());
return postResponse;
}
}
@Service注解用于类上,标记当前类是一个service类,加上该注解会将当前类自动注入到spring容器中,不需要再在applicationContext.xml文件定义bean了。
在调用该service的时候只需要将该类注入接口中即可: @Autowire 自动的找bean
if spring bean only one constructor, we can omit the annotation @Autowired