spring boot 注解
spring boot 注解
spring 会把被注解@Controller、@Service、@Repository、@Component 标注的类
纳入Spring容器中进行管理。
第7章会讲解 IoC 容器。
@Controller。
它用于标注控制器层,在MVC 开发模式中代表C(控制器)。
Model View Controller
@Controller 主要用于构建MVC 模式的程序(本书第5章会专门讲解)。
@Service。
它用于声明一个业务处理类(实现非接口类),用于标注服务层,处理业务逻辑。
例如,以下代码就是继承 ArticleService 来实现其方法。
*Description:标注为服务类
*/
@Service
public class ArticleServicelmpl implements ArticleService
@Autowired
private ArticleRepository articleRepository;
*Description:重写 service接口的实现,实现根据id 查询对象功能
@Override
public Article findArticleByld(iong id){
return articleRepository.findByld(id);}
}
(4)
@Repository。它用于标注数据访问层。
(5)
@Component。
它用于把普通POJO(Plain Ordinary Java Objects,简单的Java对象)实例化到 Spring容器中。当类不属于注解@Controller和@Service等时,就可以使用注解@Component 来标注这个类。它可配合CommandLineRunner 使用,以便在程序启动后执行一些基础任务。
Spring会把被注解@Controller、@Service、@Repository、@Component标注的类纳入Spring容器中进行管理。第7章会讲解IoC容器。
(6)@Configuration。
它用于标注配置类,并且可以由Spring容器自动处理。它作为Bean的载体,用来指示一个类声明、一个或多个@Bean 方法,在运行时为这些 Bean 生成 BeanDefinition 和服务请求。
(7)@Resource.
@Autowired与@Resource 都可以用来装配 Bean,也都可以写在字段上或Setter方法上。
public class AritcleController {
@Resource
private ArticleRepository articleRepository;
Description:新增保存方法
/
@PostMapping(“”)
public String saveArticle(Article model)l
articleRepository.save(model);
return “redirect:/article/”;
/
(8)@Autowired。
它表示被修饰的类需要注入对象。Spring 会扫描所有被@A在loC容器中找到匹配的类进行注入。被@Autowired注解后
标注
再导
1 PathVariable
(2)@PathVariable。用于获取路径中的参数。
3 Bean
(3)@Bean.
它代表产生一个Bean,并交给Spring管理。用于封装数据,一般有Setter、Getter方法、在MVC模型中,对应的是M(模型)。
4 ResponseBody
(4)@ResponseBody。
它的作用是通过转换器将控制器中方法返回的对象转换为指定的格式,然后写入Response象的body区。它常用来返回JSON/XML格式的数据。
使用此注解后,数据直接写入输入流中,不需要进行视图渲染。用法见以下代码:@GetMapping(“/test”)
@ResponseBody
public String test(){
return " test";