Spring4-IoC2-基于注解管理bean

目录

开启组件扫描

使用注解定义bean

@Autowired注入

场景一:属性注入

场景二:set注入

场景三:构造方法注入

场景四:形参注入

场景五:只有一个构造函数,无注解

场景六:@Autowired和@Qualifier注解联合

@Resource注入

场景一:根据name注入

场景二:name未知注入

场景三:其他情况

Spring全注解开发


从 Java 5 开始,Java 增加了对注解(Annotation)的支持,它是代码中的一种特殊标记,可以在编译、类加载和运行时被读取,执行相应的处理。开发人员可以通过注解在不改变原有代码和逻辑的情况下,在源代码中嵌入补充信息

Spring 从 2.5 版本开始提供了对注解技术的全面支持,我们可以使用注解来实现自动装配,简化 Spring 的 XML 配置

格式:@注解名称(属性值1=属性值...)

Spring 通过注解实现自动装配的步骤如下:

  1. 引入依赖
  2. 开启组件扫描
  3. 使用注解定义 Bean
  4. 依赖注入

子模块spring6-ioc-annotation

开启组件扫描

Spring 默认不使用注解装配 Bean,因此我们需要在 Spring 的 XML 配置中,通过 context:component-scan 元素开启 Spring Beans的自动扫描功能。开启此功能后,Spring 会自动从扫描指定的包(base-package 属性设置)及其子包下的所有类,如果类上使用了 @Component 注解,就将该类装配到容器中

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启组件扫描功能-->
    <context:component-scan base-package="com.qcby"></context:component-scan>
</beans>

注意:在使用 context:component-scan 元素开启自动扫描功能前,首先需要在 XML 配置的一级标签 <beans> 中添加 context 相关的约束

情况一:最基本的扫描方式

<context:component-scan base-package="com.qcby"></context:component-scan>

情况二:指定要排除的组件

<context:component-scan base-package="com.qcby">
        <!-- context:exclude-filter标签:指定排除规则 -->
        <!--
            type:设置排除或包含的依据
            type="annotation",根据注解排除,expression中设置要排除的注解的全类名
            type="assignable",根据类型排除,expression中设置要排除的类型的全类名
        -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <!--<context:exclude-filter type="assignable" expression="com.qcby.controller.UserController"/>-->
    </context:component-scan>

情况三:仅扫描指定组件

<context:component-scan base-package="com.qcby" use-default-filters="false">
    <!-- context:include-filter标签:指定在原有扫描规则的基础上追加的规则 -->
    <!-- use-default-filters属性:取值false表示关闭默认扫描规则 -->
    <!-- 此时必须设置use-default-filters="false",因为默认规则即扫描指定包下所有类 -->
    <!-- 
 		type:设置排除或包含的依据
		type="annotation",根据注解排除,expression中设置要排除的注解的全类名
		type="assignable",根据类型排除,expression中设置要排除的类型的全类名
	-->
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	<!--<context:include-filter type="assignable" expression="com.qcby.controller.UserController"/>-->
</context:component-scan>

使用注解定义bean

Spring 提供了以下多个注解,这些注解可以直接标注在 Java 类上,将它们定义成 Spring Bean:

注解说明
@Component该注解用于描述 Spring 中的 Bean,它是一个泛化的概念,仅仅表示容器中的一个组件(Bean),并且可以作用在应用的任何层次,例如 Service 层、Dao 层等。 使用时只需将该注解标注在相应类上即可
@Repository该注解用于将数据访问层(Dao 层)的类标识为 Spring 中的 Bean,其功能与@Component 相同
@Service该注解通常作用在业务层(Service 层),用于将业务层的类标识为 Spring 中的 Bean,其功能与 @Component 相同
@Controller该注解通常作用在控制层(如SpringMVC 的 Controller),用于将控制层的类标识为 Spring 中的 Bean,其功能与 @Component 相同

@Autowired注入

单独使用@Autowired注解,默认根据类型装配【默认是byType】

该注解可以标注在哪里?

  • 构造方法、方法、形参、属性、注解

该注解有一个required属性,默认值是true,表示在注入的时候要求被注入的Bean必须是存在的,如果不存在则报错。如果required属性设置为false,表示注入的Bean存在或者不存在都没关系,存在的话就注入,不存在的话,也不报错

场景一:属性注入

package com.qcby.autowired.controller;

import com.qcby.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {
    //注入service
    //第一种方式:属性注入
    @Autowired //根据类型找到对应对象,完成注入
    private UserService userService;

    public void add(){
        System.out.println("controller...");
        userService.add();
    }
}
package com.qcby.autowired.service;

public interface UserService {
    public void add();
}
package com.qcby.autowired.service;

import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{
    //注入dao
    //第一种方式:属性注入
    @Autowired
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("service...");
        userDao.add();
    }
}
package com.qcby.autowired.dao;

public interface UserDao {
    public void add();
}
package com.qcby.autowired.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao{
    @Override
    public void add() {
        System.out.println("dao...");
    }
}

测试:

package com.qcby;

import com.qcby.autowired.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestUserController {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        UserController controller = context.getBean(UserController.class);
        controller.add();
    }
}

场景二:set注入

package com.qcby.autowired.controller;

import com.qcby.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {

    //第二种方式 set方法注入
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void add(){
        System.out.println("controller...");
        userService.add();
    }
}
package com.qcby.autowired.service;

import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{

    //第二种方式 set方法注入
    private UserDao userDao;

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void add() {
        System.out.println("service...");
        userDao.add();
    }
}

场景三:构造方法注入

package com.qcby.autowired.controller;

import com.qcby.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {

    //第三种方式 构造方法注入
    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    public void add(){
        System.out.println("controller...");
        userService.add();
    }
}
package com.qcby.autowired.service;

import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{

    //第三种方式 构造方法注入
    private UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void add() {
        System.out.println("service...");
        userDao.add();
    }
}

场景四:形参注入

package com.qcby.autowired.controller;

import com.qcby.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {

    //第四种方式 形参注入
    private UserService userService;

    public UserController(@Autowired UserService userService) {
        this.userService = userService;
    }

    public void add(){
        System.out.println("controller...");
        userService.add();
    }
}
package com.qcby.autowired.service;

import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{

    //第四种方式 形参注入
    private UserDao userDao;

    public UserServiceImpl(@Autowired UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void add() {
        System.out.println("service...");
        userDao.add();
    }
}

场景五:只有一个构造函数,无注解

package com.qcby.autowired.controller;

import com.qcby.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserController {

    //第五种方式 只有一个有参构造,无注解
    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    public void add(){
        System.out.println("controller...");
        userService.add();
    }
}
package com.qcby.autowired.service;

import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{

    //第五种方式 只有一个有参构造,无注解
    private UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void add() {
        System.out.println("service...");
        userDao.add();
    }
}

场景六:@Autowired和@Qualifier注解联合

package com.qcby.autowired.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserRedisDaoImpl implements UserDao{
    @Override
    public void add() {
        System.out.println("dao redis...");
    }
}
package com.qcby.autowired.service;

import com.qcby.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{

    //第六种方式 @Autowired和@Qualifier注解联合,根据名称注入
    @Autowired
    @Qualifier(value = "userRedisDaoImpl")
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("service...");
        userDao.add();
    }
}

@Resource注入

@Resource注解也可以完成属性注入

@Resource和@Autowired的区别:

  • @Resource注解是JDK扩展包中的,也就是说属于JDK的一部分。所以该注解是标准注解,更加具有通用性;@Autowired注解是Spring框架自己的
  • @Resource注解默认根据名称装配byName,未指定name时,使用属性名作为name。通过name找不到的话会自动启动通过类型byType装配;@Autowired注解默认根据类型装配byType,如果想根据名称装配,需要配合@Qualifier注解一起用
  • @Resource注解用在属性上、setter方法上;@Autowired注解用在属性上、setter方法上、构造方法上、构造方法参数上

场景一:根据name注入

package com.qcby.resource.controller;

import com.qcby.resource.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller
public class UserController {

    //根据名称进行注入
    @Resource(name = "myUserService")
    private UserService userService;

    public void add(){
        System.out.println("controller...");
        userService.add();
    }
}

 

场景二:name未知注入

package com.qcby.resource.service;

import com.qcby.resource.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service(value = "myUserService")
public class UserServiceImpl implements UserService {
    //不指定名称,根据属性名称进行注入
    private UserDao myUserDao;
    
    @Override
    public void add() {
        System.out.println("service...");
        myUserDao.add();
    }
}

 

场景三:其他情况

package com.qcby.resource.controller;

import com.qcby.resource.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller
public class UserController {

    //根据类型配置
    @Resource
    private UserService userService;

    public void add(){
        System.out.println("controller...");
        userService.add();
    }
}

Spring全注解开发

全注解开发就是不再使用spring配置文件,而是写一个配置类来代替配置文件

package com.qcby.autowired.config;


import com.qcby.autowired.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration //配置类
@ComponentScan("com.qcby") //开启组件扫描
public class SpringConfig {
    public static void main(String[] args) {
        //加载配置类
        ApplicationContext context =
                new AnnotationConfigApplicationContext(SpringConfig.class);
        UserController controller = context.getBean(UserController.class);
        controller.add();
    }

}

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

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

相关文章

4款AI生成PPT工具推荐,提升工作效率

在如今的工作环境中&#xff0c;PPT制作是许多技术人员不可避免的任务&#xff0c;尤其是在汇报、展示技术方案、以及项目进展时。随着AI技术的快速发展&#xff0c;使用AI生成PPT成为了提高效率的一种新趋势。本文将介绍几款适合程序员、技术人员的AI生成PPT工具&#xff0c;帮…

C++伟大发明--模版

C起初是不受外界关注的&#xff0c;别人觉得他和C语言没有本质上的区别&#xff0c;只是方便些&#xff0c;直到祖师爷发明了模版&#xff0c;开始和C语言有了根本的区别。 我们通过一个小小的例子来搞清楚什么是模版&#xff0c;模版的作用到底有多大&#xff0c;平时我们想要…

【HarmonyOS】鸿蒙头像上传-(编辑个人信息页- 头像上传)+实时数据更新

#效果图 #思路 ##步骤&#xff1a; ###一、利用picker api选择1张图片 实例化选择器参数(使用new PhotoSelectOptions())实例化图片选择器 (使用newPhotoViewPicker() )调用图片选择器的select方法传入选择器参数完成图片选取获得结果 利用picker api选择1张图片 async sele…

【Java】线程的同步——synchronized、ReentrantLock

对同一个线程&#xff0c;能否在获取到锁以后继续获取同一个锁? 答案是肯定可以获取同一个锁。因为JVM 允许同一个线程重复获取同一个锁&#xff0c;这种能被同一个线程反复获取的锁&#xff0c;就叫做可重入锁。 一、synchronized同步锁 在 Java中synchronized 同步锁…

Windows11 WSL2的ubuntu 22.04中拉取镜像报错

问题描述 在windows11 WSL2的ubuntu 22.04中拉取镜像报错。错误为&#xff1a; Error response from daemon: Get "https://registry-1.docker.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting header…

Java音视频文件解析工具

文章目录 一 jave-all-deps二 具体用法2.1 添加依赖2.2 视频转音频2.3 视频格式转换2.4 获取视频时长 三 总结 小伙伴们知道&#xff0c;松哥平时录了蛮多视频课程&#xff0c;视频录完以后&#xff0c;就想整理一个视频文档出来&#xff0c;在整理视频文档的时候&#xff0c;就…

[Python学习日记-25] 哈希(HASH)是个什么东西?

[Python学习日记-25] 哈希&#xff08;HASH&#xff09;是个什么东西&#xff1f; 简介 哈希的特性 哈希的用途 基于 HASH 的数据类型 简介 哈希&#xff08;Hash&#xff09;&#xff0c;也称为散列&#xff0c;或音译为哈希&#xff0c;是把任意长度的输入&#xff08;又…

idea连接docker 自动化部署

进入Linux服务器 vim /lib/systemd/system/docker.service将 ExecStart/usr/bin/dockerd -H fd:// --containerd/run/containerd/containerd.sock 替换为 ExecStart/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix://var/run/docker.sock新建文件 Dockerfile配置Dockerfile文…

iOS六大设计原则设计模式

六大设计原则&#xff1a; 一、单一职责原则 一个类或者模块只负责完成一个职责或者功能。 类似于&#xff1a;UIView 和 CALayer 二、开放封闭原则 对扩展开放&#xff0c;对修改封闭。 我们要尽量通过扩展软件实体来解决需求变化&#xff0c;而不是通过修改已有的代码来…

『功能项目』窗口可拖拽脚本【59】

本章项目成果展示 我们打开上一篇58第三职业弓弩的平A的项目&#xff0c; 本章要做的事情是给坐骑界面挂载一个脚本让其显示出来的时候可以进行拖拽 创建脚本&#xff1a;DraggableWindow.cs using UnityEngine; using UnityEngine.EventSystems; public class DraggableWindo…

nodejs+express+vue教辅课程辅助教学系统 43x2u前后端分离项目

目录 技术栈具体实现截图系统设计思路技术可行性nodejs类核心代码部分展示可行性论证研究方法解决的思路Express框架介绍源码获取/联系我 技术栈 该系统将采用B/S结构模式&#xff0c;开发软件有很多种可以用&#xff0c;本次开发用到的软件是vscode&#xff0c;用到的数据库是…

烧结银胶成为功率模块封装新宠

烧结银胶成为功率模块封装新宠 在科技日新月异的今天&#xff0c;材料科学作为推动工业进步的重要基石&#xff0c;正不断涌现出令人瞩目的创新成果。其中&#xff0c;善仁烧结银胶作为微电子封装领域的一项重大突破&#xff0c;正以其独特的性能优势&#xff0c;逐步成为连接…

Docker torchserve 部署模型流程

1.拉取官方镜像 地址: https://hub.docker.com/r/pytorch/torchserve/tags docker pull pytorch/torchserve:0.7.1-gpu2. docker启动指令 CPU docker run --rm -it -d -p 8380:8080 -p 8381:8081 --name torch-server -v /path/model-server/extra-files:/home/model-serve…

MySQL日志binlog和redo log区别

MySQL binlog简介 MySQL中有两类日志&#xff1a;binlog和redo log&#xff0c;分别有不同的作用和解决问题。binlog是归档日志&#xff0c;在MySQL server层的日志&#xff0c;适用于所有存储引擎&#xff0c;redo log是innodb特有日志用于crash-safe时恢复数据。 binlog和r…

【RabbitMQ】工作模式

工作模式概述 简单模式 简单模式中只存在一个生产者&#xff0c;只存在一个消费者。生产者生产消息&#xff0c;消费者消费消息。消息只能被消费一次&#xff0c;也称为点对点模式。 简单模式适合在消息只能被单个消费者处理的场景下存在。 工作队列模式&#xff08;Work Qu…

Apache SeaTunnel Zeta引擎源码解析(三) Server端接收任务的执行流程

作者&#xff1a;刘乃杰 编辑整理&#xff1a;曾辉 引入 本系列文章是基于 Apache SeaTunnel 2.3.6版本&#xff0c;围绕Zeta引擎给大家介绍其任务是如何从提交到运行的全流程&#xff0c;希望通过这篇文档&#xff0c;对刚刚上手SeaTunnel的朋友提供一些帮助。 我们整体的文…

linux文件系统权限详解

注:目录的执行权限代表是否可以进入。 一、文件权限控制对文件的访问: 可以针对文件所属用户、所属组和其他用户可以设置不同的权限 权限具有优先级。user权限覆盖group权限,后者覆盖other权限。 有三种权限类别:读取、写入和执行 读权限:对文件:可读取文件…

[SAP ABAP] 修改内表数据

1.利用关键字修改数据 语法格式 MODIFY TABLE <itab> FTOM <wa> [TRANSPORTING f1 f2...].<itab>&#xff1a;代表内表 <wa>&#xff1a;代表工作区 示例1 内表修改前的数据 将上述数据行中的AGE字段值更改为25&#xff0c;SEX字段值更改为女 输出结…

5.基础漏洞——文件上传漏洞

目录 一.文件上传漏洞原理 二.文件上传漏洞条件&#xff1a; 三.上传限制手段分为两大类 (1)客户端校验 (2)服务端校验 四.具体实现 1.文件上传漏洞——绕过JS检测 2.文件上传漏洞——绕过MIME类型检测 3.文件上传漏洞——绕过黑名单检测 绕过方式:(1) 绕过方式:(2) …

城市脉络下的空间句法:整合度与选择度的深度解析

上回写过一篇&#xff0c;基于空间句法的路网整合度、选择度分析&#xff0c;当时碍于篇幅和侧重点&#xff0c;主要讲了如何安装sDNA这个插件来实现路网的整合度、选择度分析&#xff0c;并且分析部分也只是画了几条简单的线段&#xff0c;这次我们深化一下原理和指标的解析&a…