能@Component,@Repository并@Service注释互换在Spring中,还是他们提供任何特殊的功能,除了作为一个符号设备?
换句话说,如果我有一个Service类并且我将注释更改@Service为@Component,它仍然会以相同的方式运行吗?
或者注释是否也会影响类的行为和功能?
我正在学习有关Spring Boot和JPA,Spring Data Rest,H2数据库的知识,并且找到了一个教程。我试图理解它,这是一个简单的例子,但我不明白。为什么没有必要放置@Repository或@Component加入AlienRepo类?
回购对象被注入到AlienController类中,从以前的教程中我知道您需要使用@Component或@Repository。我认为使用此批注是强制性的。
控制器:
package com.dgs.springbootjpa.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.dgs.springbootjpa.dao.AlienRepo;
import com.dgs.springbootjpa.model.Alien;
@Controller
public class AlienController {
@Autowired
AlienRepo repo;
@RequestMapping("/")
public String home() {
return "home.jsp";
}
@RequestMapping("/addAlien")
public String addAlien(Alien alien) {
repo.save(alien);
return "home.jsp";
}
}
Run Code Online (Sandbox Code Playgroud)
POJO:
package com.dgs.springbootjpa.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Alien {
@Id
private int aid;
private String aname;
public int getAid() {
return aid; …Run Code Online (Sandbox Code Playgroud)