五大类注解联系

83 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第20天,点击查看活动详

大家好,我是bug郭,一名双非科班的在校大学生。对C/JAVA、数据结构、Spring系列框架、Linux及MySql、算法等领域感兴趣,喜欢将所学知识写成博客记录下来。 希望该文章对你有所帮助!如果有错误请大佬们指正!共同学习交流

作者简介:

@Service(服务存储)

注册bean

package com;

import org.springframework.stereotype.Service;

@Service // @Service 注解注册对象!
public class UserService {
    public  void sayHi(){
        System.out.println("Hello Service注解!");
    }
}

读取bean

在这里插入图片描述

@Configuration(配置存储)

package com;

import org.springframework.context.annotation.Configuration;

@Configuration //Configuration注解注册bean对象
public class UserConfiguration {
    public void sayHi(){
        System.out.println("Hello Configuration注解!");
    }
}

在这里插入图片描述

@Repository(仓库存储)

package com;

import org.springframework.stereotype.Repository;

@Repository //@Respository 注解注册对象
public class UserRepository {
    public void sayHi(){
        System.out.println("Hello Respository注解!");
    }
}

在这里插入图片描述

@Component(组件存储)

package com;

import org.springframework.stereotype.Component;

@Component //Component注解注册对象!
public class UserComponent {
    public void sayHi(){
        System.out.println("Hello Component注解!");
    }
}

在这里插入图片描述

5大类注解联系

在这里插入图片描述

可以看到这5大类注解使用方式一样,都可以对对象进行注册! 而且注册的方式都一样,既然如此为何还需要5个注解呢?

我们联系实际生活中的车牌号,我们虽然车牌号的功能都是一样,但是不同地区都有自己的车牌号!我们通过车牌号就可以分辨出这车来自哪里! 而这里5大类注解作用也是如此,我们通过类注解,可以知道当前类的用途! 例如;

@Controller:表示业务逻辑层 @Service:服务层 @Repository:持久层 @Configuration:配置层

程序的工程分层,调用流程如下: 在这里插入图片描述 我们拿去银行办业务做类比:

@Controller层就是保安,先要进行检查验证,然后到达Service服务厅询问业务,不同的业务来到Repository,不同的窗口,然后进行相应的工作人员办理业务!

类注解之前联系: 在这里插入图片描述 可以看到其他4个注解都是Component注解的子类!