Spring种存取Bean的5种注解

存取Bean的五种注解

  • 存储Bean对象两种方式
    • 1.添加一行bean
    • 2.使用注解的方式(5大注解)
      • @Controller(控制器存储)
      • @Service(服务存储)
      • @Repository(仓库存储)
      • @Component(组件存储)
      • @Configuration(配置存储)
      • 方法注解 @Bean
  • 获取Bean对象(三种)
    • 1.属性注入
    • 2.setter注入
    • 3.构造方法注入
    • 三种注入的优缺点(面试)
    • @Resource 和 @Autowired区别

先给大家看看我的命名规范
在这里插入图片描述

存储Bean对象两种方式

1.添加一行bean

在spring-config.xml中添加一个bean 把对象注册给spring。
这种方法在有多个对象的时候 也得一行一行的存进去。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="user" class="User"></bean>
</beans>

2.使用注解的方式(5大注解)

2.第二种方法是使用注解 在有很多个对象需要存储的时候就不用一行一行注册了,使用前需要先在xml中配置一下扫描路径,这样注解才能识别出来类并存储到spring。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <content:component-scan base-package="com.demo.component"></content:component-scan>
</beans>

@Controller(控制器存储)

表示的是业务逻辑层,会判断前端发来的请求是否符合规范。

@Service(服务存储)

表示的是服务层,用来分配用户需要使用的功能。

@Repository(仓库存储)

表示的是持久层,直接和数据库交互,一张表一个@Repository。

@Component(组件存储)

表示的是公共工具层,用来添加一些公共的方法。

@Configuration(配置存储)

表示的是配置层,用来配置一些项目信息。

方法注解 @Bean

演示:
(配置了扫描路径可以使用@Bean)

package com.demo.component;

import com.demo.model.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;

@Controller
public class BController {//只是我的包装类 目的是
    //获取bean 注释一下 使用Bean注解 需要配合5大注解一起用。
    //可以加入name参数 重新命名 因为如果有多个包装类都要使用这个Bean对象就有问题 名字都一样 到底拿哪一个Bean

    @Bean
    public Student student() {
        Student student = new Student();
        student.setId(1);
        student.setAge(18);
        student.setName("zyz");
        return student;
    }
}

使用@Bean注解来把Bean中的对象。 但是使用Bean注解的时候配合这五大注解来用。

在@Bean中 还有命名规范的问题。
Student类
在这里插入图片描述

package com.demo.model;

public class Student {
    private  int id;
    private  String name;
    private  int age;

    public int getId() {
        return id;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

BController类
在这里插入图片描述

package com.demo.component;

import com.demo.model.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;

@Controller
public class BController {
    //获取bean 注释一下 使用Bean注解 需要配合5大注解一起用。
    //可以加入name参数 重新命名 因为如果有多个包装类都要使用这个Bean对象就有问题 名字都一样 到底拿哪一个Bean

    @Bean
    public Student student() {
        //构造对象的 伪代码
        Student student = new Student();
        student.setId(1);
        student.setAge(18);
        student.setName("zyz");
        return student;
    }
}

App类
在这里插入图片描述
我们需要在APP类中启动Spring然后在BController类中拿到Bean对象(Student)。

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
Student student = context.getBean("student",Student.class);//拿的是BController中的对象
System.out.println(student);
  • 需要注意的是Bean的命名规则是默认为类名的小写
  • 如果类首字母大写/小写,那么命名就需要是小写的,比如类是Student 那么命名就要是student。
  • 如果类 首字母和第二个字母都是大写的话,命名就不变。
  • 如果@Bean方法注解 加入了name 那么就需要按照name来命名,不能使用原来默认的名字。代码如下👇
package com.demo.component;
import com.demo.model.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;

@Controller
public class StudentBeans {//只是一个包装类 我目的是拿到Student对象
//获取bean 注释一下 使用Bean注解 需要配合5大注解一起用。
    //可以加入name参数 重新命名 因为如果有多个包装类都要使用这个Bean对象就有问题 名字都一样 到底拿哪一个Bean
    @Bean(name = {"s1","s2"})//s1s2命名 使用哪个都可以
    public Student st() {
        //构造对象的 伪代码
        Student student = new Student();
        student.setId(1);
        student.setAge(18);
        student.setName("zyz");
        return student;
    }
}
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        //默认的命名是将类的首字母小写
        //1.如果类名首字母是大写或者小写 则都是小写 2.如果类名前两个字母是小写 则命名不变 这是JVM来规定的 不是Spring进行规定的 源码下在rt.jar包里 可以说明
        ArtController artController = context.getBean("artController",ArtController.class);
        System.out.println(artController.Say());

        Student student = context.getBean("s1",Student.class);//拿的是StudentBeans中的对象
        Student student1 = context.getBean("student",Student.class);//拿的是BController中的对象
        //如果对Bean注解 加入了name 那就只能使用那个name 不能使用原来的名字
        System.out.println(student);

获取Bean对象(三种)

获取Bean对象也叫对象装配,把对象拿出来放到类中,所以也叫对象注入,ApplicationContext 中getBean是在main把对象从Spring上下文中拿出来需要运行使用,

如果我们需要把一个类注入到另一个类中 就需要使用对象注入。
下面的例子是将StudentService类注入到StudentController类中

1.属性注入

使用@Autowired

package com.demo.controller;

import com.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class StudentController {
    //1.使用属性注入的方法来获取Bean 从Spring中 获取Bean
    //另一种获取Bean对象的方法(对象装配)
    @Autowired
    private StudentService studentService;


    public void Say() {
        //调用 service的方法
        studentService.Say();
    }
}

2.setter注入

package com.demo.controller;

import com.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class StudentController {
    //1.使用属性注入的方法来获取Bean 从Spring中 获取Bean
    //另一种获取Bean对象的方法(对象装配)
//    @Autowired
//    private StudentService studentService;

    //2.构造方法注入
    private StudentService studentService;
    
    @Autowired
    public  StudentController (StudentService studentService) {
        this.studentService = studentService;
    }


    public void Say() {
        //调用 service的方法
        studentService.Say();
    }
}

3.构造方法注入

是Spring推荐的使用方法 其中只有一个构造方法的时候@Autowired可以省略

package com.demo.controller;

import com.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class StudentController {
    //1.使用属性注入的方法来获取Bean 从Spring中 获取Bean
    //另一种获取Bean对象的方法(对象装配)
//    @Autowired
//    private StudentService studentService;

    //2.构造方法注入
    private StudentService studentService;
    
    @Autowired
    public  StudentController (StudentService studentService) {
        this.studentService = studentService;
    }


    public void Say() {
        //调用 service的方法
        studentService.Say();
    }
}

三种注入的优缺点(面试)

  • 属性注入:
  • 优点:使用方便,简单。
  • 缺点:1.不能注入final修饰的不可变对象。2.只用用于Ioc容器。3.更加不符合单一设计原则(类)
  • setter注入:
  • 优点:更加符合单一设计原则(方法)
  • 缺点:不能注入final修饰的不可变对象,注入的对象可以修改,因为set是一个普通方法,调用的时候就可以修改。
  • 构造方法注入(Spring4开始 官方的推荐):
  • 优点:可以注入不final修饰的不可变对象,意味着对象是不可被修改的, 通用性好,对象完全被初始化。
  • 缺点:不是那么方便。

在开发中使用属性注入比较多。

@Resource 和 @Autowired区别

相同点:都是依赖注入
不同点:1.@Resource是JDK提供的,@Autowired是Spring框架中的。2.@Resource源码中 有更多的参数和方法,@Autowired中只有一个required参数。2.@Resource不支持构造方法注入。4.同一类型多个Bean要返回的时候 可以使用@Resource中可以加入name @Resource(name=" “) 或者 使用@Qualifier(value=” ")
代码如下👇
在这里插入图片描述
StudentBeans类注入到UserController中

package com.demo.component;
import com.demo.model.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;

@Controller
public class StudentBeans {//只是一个包装类 我目的是拿到Student对象
        @Bean
    public Student st1() {

        Student student = new Student();
        student.setId(1);
        student.setAge(18);
        student.setName("zyz");
        return student;
    }

        @Bean
    public Student st2() {

        Student student = new Student();
        student.setId(1);
        student.setAge(18);
        student.setName("李四");
        return student;
    }

}

UserController类

package com.demo.controller;

import com.demo.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller
public class UserController {
    //将StudentBeans中的对象注入到这个类中 因为查找的时候先通过类型查找
    //StudentBeans中的Bean对象有两个 是相同类型的 这时候就分不清应该取哪个
    //就要使用@Resource 或者 @Qualifier来写入名称

    //1.
//    @Resource(name = "st1")
//    private Student student;
//
//    public Student getStudent() {
//        return student;
//    }

    //2.
    @Autowired
    @Qualifier(value = "st1")
    private Student student;

    public Student getStudent() {
        return student;
    }
}

在2个Bean对象类型相同的时候,对象注入的时候获取对象 就不知道应该拿哪一个对象,这时候就使用@Resource 或者 @Qualifier 可以添加想要获取的Bean对象的名称,这里拿的是st1。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/13722.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

springboot-分页功能

1.分页功能的作用 分页功能作为各类网站和系统不可或缺的部分&#xff08;例如百度搜索结果的分页等&#xff09; &#xff0c;当一个页面数据量大的时候分页作用就体现出来的&#xff0c;其作用有以下5个。 &#xff08;1&#xff09;减少系统资源的消耗 &#xff08;2&#…

Vue 3组件传值 、组件通信

本文采用<script setup />的写法&#xff0c;比options API更自由。那么我们就来说说以下七种组件通信方式&#xff1a; props emit v-model refs provide/inject eventBus vuex/pinia 举个例子 本文将使用下面的演示&#xff0c;如下图所示&#xff1a; 上图中…

mybatis粗心使用导致内存溢出

现象 服务响应变慢&#xff0c;线程日志也出现Java heap space内存溢出的错误&#xff0c;这个服务属于基础业务服务&#xff0c;出现问题要尽快的排查 分析 因为设置了gc日志和jmap启动相关参数 所以我们进行分析&#xff0c;这里模拟线上环境将堆大小参数调整到了128m&am…

【Linux】权限管理

文章目录 &#x1f4d6; 前言1. 什么是权限2. 权限管理2.1 Linux的用户分类&#xff1a;2.2 Liunx文件的分类&#xff1a;2.3 文件的访问权限2.4 文件访问权限的相关设置方法&#xff1a;chmod对文件权限的修改chown / chgrp 2.5 以八进制修改文件权限&#xff1a;2.6 默认权限…

Springsecurity课程笔记06-13章基于数据库的方法授权

动力节点Springsecurity视频课程 6 密码处理 6.1 为什么要加密&#xff1f; csdn 密码泄露事件 泄露事件经过&#xff1a;https://www.williamlong.info/archives/2933.html 泄露数据分析&#xff1a;https://blog.csdn.net/crazyhacking/article/details/10443849 6.2加密…

IJKPLAYER源码分析-常用API

前言 本文简要介绍IJKPLAYER的几个常用API&#xff0c;以API使用的角度&#xff0c;来审视其内部运作原理。这里以iOS端直播API调用切入。 调用流程 init 创建播放器实例后&#xff0c;会先调用init方法进行初始化&#xff1a; - (IJKFFMediaPlayer *)init {self [super ini…

计算机网络复习题+答案

文章目录 导文题目一、单项选择题二、填空题三、判断改错题,判断下列命题正误,正确的在其题干后的括号内打“√”,错误的打“”,并改正。四、名词解释五、简答题六、应用题导文 计算机网络复习题 题目 一、单项选择题 在应用层协议中,主要用于IP地址自动配置的协议是: (…

文案自动修改软件-文案自动改写的免费软件下载

文章生成器ai写作机器人 随着人工智能技术的飞速发展&#xff0c;越来越多的新型产品被推向市场。其中&#xff0c;文章生成器AI写作机器人是一个备受关注的新兴行业。它使用机器学习和自然语言处理等技术&#xff0c;为用户自动生成高质量的文章和内容&#xff0c;帮助用户在…

Python——第2章 数据类型、运算符与内置函数

目录 1 赋值语句 2 数据类型 2.1 常用内置数据类型 2.1.1 整数、实数、复数 2.1.2 列表、元组、字典、集合 2.1.3 字符串 2.2 运算符与表达式 2.2.1 算术运算符 2.2.2 关系运算符 2.2.3 成员测试运算符 2.2.4 集合运算符 2.2.5 逻辑运算符 2.3 常用内置…

本地搭建属于自己的ChatGPT:基于PyTorch+ChatGLM-6b+Streamlit+QDrant+DuckDuckGo

本地部署chatglm及缓解时效性问题的思路&#xff1a; 模型使用chatglm-6b 4bit&#xff0c;推理使用hugging face&#xff0c;前端应用使用streamlit或者gradio。 微调对显存要求较高&#xff0c;还没试验。可以结合LoRA进行微调。 缓解时效性问题&#xff1a;通过本地数据库…

Mybatis高级映射及延迟加载

准备数据库表&#xff1a;一个班级对应多个学生。班级表&#xff1a;t_clazz&#xff1b;学生表&#xff1a;t_student 创建pojo&#xff1a;Student、Clazz // Student public class Student {private Integer sid;private String sname;//...... }// Clazz public class Cla…

Flutter PC桌面端 控制应用尺寸是否允许放大缩小

一、需求 桌面端中&#xff0c;登录、注册、找回密码页面不允许用户手动放大缩小&#xff0c;主页面允许 二、插件 window_manager 使用教程请参照这篇博客&#xff1a;Flutter桌面端开发——window_manager插件的使用 题外话&#xff1a; 之前使用的是bitsdojo_window插件…

[golang gin框架] 25.Gin 商城项目-配置清除缓存以及前台列表页面数据渲染公共数据

配置清除缓存 当进入前台首页时,会缓存对应的商品相关数据,这时,如果后台修改了商品的相关数据,缓存中的对应数据并没有随之发生改变,这时就需要需改对应的缓存数据,这里有两种方法: 方法一 在管理后台操作直接清除缓存中的所有数据,当再次访问前台首页时,就会先从数据库中获取…

记frp内网穿透配置

这两天由于想给客户看一下我们的系统&#xff0c;于是想到用内网穿透&#xff0c;但是怎么办呢&#xff0c;没有用过呀&#xff0c;于是各处找资料&#xff0c;但是搞完以后已经不记得参考了那些文档了&#xff0c;对不起各位大神&#xff0c;就只能写出过程和要被自己蠢死的错…

初识C++(二)

在初识c&#xff08;一&#xff09;当中我们已经向大家介绍了四个c和C语言不同的使用方法。接下来我们再来向大家介绍另外的一些新的c语言的使用方法。 &#x1f335;引用 简单一点来说引用就是给已存在的变量起一个别名。这个别名通常的作用和C语言当中的指针类似。我们可以通…

牛客网刷题总结

1.利用%符号获取特定位数的数字。 2.强制类型转换 &#xff08;将float转换为int &#xff09; 3.计算有关浮点型数据时&#xff0c;要注意你计算过程中所有的数据都是浮点型 4.0/3.0 ! 4/3 4.通过位操作符实现输出2的倍数&#xff08;对于位操作符不熟悉的小伙伴可以看看我…

基于Java+SpringBoot+vue实现图书借阅和销售商城一体化系统

基于JavaSpringBootvue实现图书借阅和销售商城一体化系统 博主介绍&#xff1a;5年java开发经验&#xff0c;专注Java开发、定制、远程、指导等,csdn特邀作者、专注于Java技术领域 作者主页 超级帅帅吴 Java项目精品实战案例《500套》 欢迎点赞 收藏 ⭐留言 文末获取源码联系方…

电脑系统错误怎么办?您可以看看这5个方法!

案例&#xff1a;电脑出现系统错误该如何解决&#xff1f; 【这几天长时间使用我的电脑&#xff0c;导致它的系统出现了错误。有没有小伙伴知道如何解决电脑系统出错的问题&#xff1f;求一个能快速解决的方法。】 电脑系统出现错误是使用电脑时难免会遇到的问题之一&#xf…

【C++初阶】C++入门(二):引用内联函数auto关键字范围for循环(C++11)指针空值nullptr

​ ​&#x1f4dd;个人主页&#xff1a;Sherry的成长之路 &#x1f3e0;学习社区&#xff1a;Sherry的成长之路&#xff08;个人社区&#xff09; &#x1f4d6;专栏链接&#xff1a;C初阶 &#x1f3af;长路漫漫浩浩&#xff0c;万事皆有期待 上一篇博客&#xff1a;【C初阶】…

MySQL数据库学习笔记之存储引擎

存储引擎 MySQL体系结构 连接层 最上层是一些客户端和连接服务&#xff0c;主要完成一些类似于连接处理、授权认证、以及相关的安全方案。服务器也会为安全接入的每个客户端验证它所具有的操作权限。 服务层 第二层架构主要完成大多数的核心服务功能&#xff0c;如SQL接口&am…