Spring种存取Bean的5种注解

news2024/10/6 10:41:48

存取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.coloradmin.cn/o/455946.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

自动驾驶TPM技术杂谈 ———— CCRT验收标准(测试项目)

文章目录 试验项目行车辅助跟车能力测试方法前车静止识别与响应前车低速识别与响应前车减速识别与响应前车切入识别与响应前车切出识别与响应跟随前车启停 单车道组合控制能力测试方法车道居中保持交通拥堵辅助高速驾驶辅助 换道辅助能力测试方法无干扰车换道有干扰车换道 泊车…

《面试1v1》java泛型

我是 javapub&#xff0c;一名 Markdown 程序员从&#x1f468;‍&#x1f4bb;&#xff0c;八股文种子选手。 面试官&#xff1a;小伙子,说实话,泛型这个机制一开始我也是一头雾水,搞不太明白它到底要解决什么问题。你能不能不那么书呆子,给我普普通通地讲一讲泛型? 候选人…

真正的进步,是创业者和员工的共同进步

再伟大的事业&#xff0c;也是由人一点一滴创造出来的。 人&#xff0c;是企业中最基础的存在&#xff0c;下层基础决定上层建筑&#xff0c;管理公司企业&#xff0c;也是人与人之间的交流问题。 创业十余年&#xff0c;与市场打交道&#xff0c;也与人打交道。 对外&#x…

ArduPilot Kakute F7 AIO DIYF450 之GPS配置

ArduPilot Kakute F7 AIO DIYF450 之GPS配置 1. 源由2. 步骤2.1 模块预测试2.2 物理连接2.3 UART配置2.4 Compass使能2.5 GPS使能2.6 校准Compass 3. GPS & Compass配置效果3.1 Mission Planner界面3.2 QGroundControl界面3.3 ArduPilot配置修改 4. 参考资料 1. 源由 之前…

选址-路径问题(Location-Routing Problem, LRP)

今天为大家介绍的是选址-路径问题(Location-Routing Problem, LRP)&#xff0c;首先上目录 目录 问题简介 基础模型、扩展问题及应用 算法 参考文献 1 问题简介 为了更好地了解这个问题&#xff0c;我们不妨当一波老板。 想象一下我们是经营一家口罩生产企业的老板&am…

RocketMQ基本概念

RocketMQ 一 引言 Message Queue&#xff08;消息 队列&#xff09;&#xff0c;从字⾯上理解&#xff1a;⾸先它是⼀个队列。先进先出的数据结构——队列。消息队列就是所谓的存放消息的队列。 消息队列解决的不是存放消息的队列的⽬的&#xff0c;解决的是通信问题&#x…

C语言实现顺序表--数据结构

魔王的介绍&#xff1a;&#x1f636;‍&#x1f32b;️一名双非本科大一小白。魔王的目标&#xff1a;&#x1f92f;努力赶上周围卷王的脚步。魔王的主页&#xff1a;&#x1f525;&#x1f525;&#x1f525;大魔王.&#x1f525;&#x1f525;&#x1f525; ❤️‍&#x1…

项目管理中引入PMO的应用研究——以H研究所为例

摘 要 本文从项目管理办公室&#xff08;PMO&#xff09;的基本内涵出发&#xff0c;探讨了PMO在以“项目”为主要工作组织方式的H研究所应用过程中发挥的作用、具有的优势、取得的成效与存在的不足&#xff0c;从而实现为企业培养专业的项目经理团队&#xff0c;为业务部门定…

Ubuntu20.04安装CUDA和CUDNN

CUDA是GPU深度学习的运行库&#xff0c;那么cuDNN就是训练加速工具&#xff0c;两者要相互配合使用&#xff0c;所以一般机器学习需要训练引擎(tensorflow-gpu) CUDA cuDNN使用。想不安装cuDNN是不可以的&#xff0c;而且cuDNN版本要和CUDA版本相互搭配。 1、前置工作 查看…

最新动态 | 大势智慧参加广东省应急测绘保障与安全生产演练

4月20日&#xff0c;2023年度广东省应急测绘保障与安全生产演练在台山市赤溪镇鱼塘湾举行。本次演练由广东自然资源厅主办&#xff0c;广东省国土资源测绘院、江门市自然资源局和台山市人民政府承办。在省市各指导单位与参演单位的多方协同与指挥下&#xff0c;应急测绘保障与安…

常用PLC学习资料下载地址

常见PLC的资料一般在官网都可以找到&#xff0c;今天整理一下&#xff0c;把西门子、三菱、欧姆龙、汇川四家品牌的官方下载地址直接贴出来供大家直接使用。 1、汇川技术官方网站 汇川技术 - 推进工业文明 共创美好生活 (inovance.com)https://www.inovance.com/2、汇川技术资料…

TCP重传、滑动窗口、流量控制、拥塞控制

目录 重传机制 #超时重传 SACK 方法 Duplicate SACK 滑动窗口 流量控制 窗口关闭 拥塞控制 慢启动 拥塞避免算法 拥塞发生 快速恢复 重传机制 TCP 实现可靠传输的方式之一&#xff0c;是通过序列号与确认应答。 在 TCP 中&#xff0c;当发送端的数据到达接收主机时…

rancher部署flink集群

rancher版本&#xff1a;v2.6.8 k8s版本&#xff1a;v1.22.13rke2r1 flink集群版本&#xff1a;1.15.0 flink安装模式&#xff1a;session cluster 写在前面&#xff1a;因为参照官网的说明安装过程中出现了很多问题&#xff0c;特记录于此&#xff0c;避免后续重复踩坑 目…

FE_CSS 精灵图技术 字体图标 CSS三角

一个网页中往往会应用很多小的背景图像作为修饰&#xff0c;当网页中的图像过多时&#xff0c;服务器就会频繁地接收和发送请求图片&#xff0c;造成服务器请求压力过大&#xff0c;这将大大降低页面的加载速度。 因此&#xff0c;为了有效地减少服务器接收和发送请求的次数&a…

国内申请日本专利有哪些流程?

日本2004年修订的实用新型法已经于2005年4月1日生效&#xff0c;在日本&#xff0c;“专利”这一概念限于发明&#xff0c;实用新型和外观设计均不称为专利。实用新型授权后&#xff0c;就叫实用新型权&#xff0c;并不叫专利权。而且&#xff0c;发明、实用新型和外观设计是“…

掘金Tiktok电商比亚马逊刺激多了

鑫优尚电子商务&#xff1a;万亿跨境电商市场&#xff0c;聚光灯照在了Tiktok&#xff08;抖音海外版&#xff09;身上。 美国、巴西、俄罗斯、越南……2017年年末才正式出海的Tiktok&#xff0c;仅在2年后便覆盖了150个国家和地区&#xff0c;多次登顶App Store下载量首位。 …

使用 Vaex 处理具有 2 亿行的数据集

在这篇文章中,我们生成了 2 亿条时序人工数据,有 4 列,大小接近 12GB。使用 Pandas 库无法读取数据集并对其进行探索和可视化。与 pandas 相比,能够将字符串处理速度提高10-1000 倍。比spark快近十倍。 Pandas是用于数据科学案例研究的最受欢迎的库之一。它是探索性数据分…

rtthread默认网卡的操作

设置网卡优先级 在 RT-Thread 操作系统中&#xff0c;可以通过修改网卡的优先级来设置默认网卡。优先级越高的网卡会被优先选择为默认网卡。 下面介绍一些设置默认网卡优先级的方法&#xff1a; 在 RT-Thread 的网络配置文件 rtconfig.h 中&#xff0c;可以通过修改 NETIF_P…

SAP CAP篇一:快速创建一个Service,基于Java的实现

这个博客上&#xff0c;还没有写过SAP技术栈的东西&#xff0c;这次开个头&#xff0c;写个最近研究SAP CAP的摸索过程。虽然SAP CAP&#xff08;Cloud Application Model&#xff09;关注在Cloud的开发&#xff0c;我这些文章里面还是偏重本地上的尝试。 文章目录 前置内容现在…

当Kotlin Flow与Channel相逢

Flow之所以用起来香&#xff0c;Flow便捷的操作符功不可没&#xff0c;而想要熟练使用更复杂的操作符&#xff0c;那么需要厘清Flow和Channel的关系。 本篇文章构成&#xff1a; 1. Flow与Channel 对比 1.1 Flow核心原理与使用场景 原理 先看最简单的Demo&#xff1a; fun…