9-组件扫描(注解开发)

2023-11-09

组件扫描(component scanning): Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件.
特定组件包括:
@Component: 基本注解, 标识了一个受 Spring 管理的组件
@Respository: 标识持久层组件
@Service: 标识服务层(业务层)组件
@Controller: 标识表现层组件
对于扫描到的组件, Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件的名称
特定的组件注入:
@Autowired:注解自动装配具有兼容类型的单个 Bean属性
@Resource:(这个注解属于J2EE的),默认按照名称进行装配
步骤:
1.加入context命名空间
2.开启扫描
3. 在类上使用以上四个组件注解

以下实例仅仅是为了演示注解,跟业务无关。

1.pom.xml依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring-8</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>5.2.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

2.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:context="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
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解扫描-->
    <context:component-scan base-package="com.qwy"/>

</beans>

3.POJO

package com.qwy.bean;

/**
 * @author qwy
 * @create 2021-04-22 19:35
 **/
public class Users {
}

4. DAO接口

package com.qwy.dao;

import com.qwy.bean.Users;

/**持久层接口
 * @author qwy
 * @create 2021-04-22 19:37
 **/
public interface UsersDAO {
    //添加用户
    public int save(Users users);
    //其他持久层方法
}

5.DAO接口实现类

package com.qwy.dao.impl;

import com.qwy.bean.Users;
import com.qwy.dao.UsersDAO;
import org.springframework.stereotype.Repository;

/**持久层实现类
 * @author qwy
 * @create 2021-04-22 19:38
 * @Repository  :将实现类交给spring容器管理
 *          value: 指定实例名称,默认为类名首字母小写
 **/
@Repository(value = "usersDAO")
public class UsersDAOImpl implements UsersDAO {
    public int save(Users users) {
        System.out.println("UsersDAOImpl.save");
        return 0;
    }
}

6.service接口

package com.qwy.service;

import com.qwy.bean.Users;

/**
 * @author qwy
 * @create 2021-04-22 19:35
 **/
public interface UsersService {
    //添加用户
    public int save(Users users);
    //其他方法
}

7. service接口实现类

package com.qwy.service.impl;

import com.qwy.bean.Users;
import com.qwy.dao.UsersDAO;
import com.qwy.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author qwy
 * @create 2021-04-22 19:36
 *  @Service :将该类交给spring管理
 *         value:给该实例起名,默认为类名首字母小写
 *
 *
 **/
@Service(value = "usersService")
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersDAO usersDAO;
    public int save(Users users) {
        usersDAO.save(users);
        System.out.println("UsersServiceImpl.save");
        return 0;
    }
}

8.控制层

package com.qwy.controller;

import com.qwy.bean.Users;
import com.qwy.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * @author qwy
 * @create 2021-04-22 19:43
 *  @Controller  :将该类交给spring容器
 **/
@Controller
public class UsersController {
    //注入UsersServiceImpl的实例
    @Autowired
    private UsersService usersService;
    public  String save(Users users){
        usersService.save(users);
        System.out.println("UsersController.save");
        return "hello";
    }
}

9.测试类

package com.qwy.test;

import com.qwy.bean.Users;
import com.qwy.controller.UsersController;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author qwy
 * @create 2021-04-22 19:45
 **/
public class TestAnnotation {
    private ApplicationContext  ac= new ClassPathXmlApplicationContext("applicationContext.xml");

    @Test
    public void test1(){
        UsersController usersController = ac.getBean("usersController", UsersController.class);
        usersController.save(new Users());
    }
}

执行结果:
UsersDAOImpl.save
UsersServiceImpl.save
UsersController.save

通过执行结果发现。DAO,Service,Controller已经交给spring管理(IOC),依赖的对象也已经注入(DI).

10.补充

1

<context:component-scan base-package=“com.qwy”/>
base-package 属性指定一个需要扫描的基类包,Spring 容器将会扫描这个基类包里及其子包中的所有类.
当需要扫描多个包时, 可以使用逗号分隔.
如果仅希望扫描特定的类而非基包下的所有类,可使用 resource-pattern 属性过滤特定的类,示例:
<context:component-scan base-package=“com.qwy” resource-pattern=“controller/*.class”/>
另外:
context:include-filter 子节点表示要包含的目标类
context:exclude-filter 子节点表示要排除在外的目标类
context:component-scan 下可以拥有若干个 context:include-filter 和 context:exclude-filter 子节点

2

Autowired 注解自动装配具有兼容类型的单个 Bean属性
构造器, 普通字段(即使是非 public), 一切具有参数的方法都可以应用@Authwired 注解
默认情况下, 所有使用 @Authwired 注解的属性都需要被设置. 当 Spring 找不到匹配的 Bean 装配属性时, 会抛出异常, 若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false
默认情况下, 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作. 此时可以在 @Qualifier 注解里提供 Bean 的名称. Spring 允许对方法的入参标注 @Qualifiter 已指定注入 Bean 的名称
@Authwired 注解也可以应用在数组类型的属性上, 此时 Spring 将会把所有匹配的 Bean 进行自动装配.
@Authwired 注解也可以应用在集合属性上, 此时 Spring 读取该集合的类型信息, 然后自动装配所有与之兼容的 Bean.
@Authwired 注解用在 java.util.Map 上时, 若该 Map 的键值为 String, 那么 Spring 将自动装配与之 Map 值类型兼容的 Bean, 此时 Bean 的名称作为键值。
Spring 还支持 @Resource 和 @Inject 注解,这两个注解和 @Autowired 注解的功用类似
@Resource 注解要求提供一个 Bean 名称的属性,若该属性为空,则自动采用标注处的变量或方法名作为 Bean 的名称
@Inject 和 @Autowired 注解一样也是按类型匹配注入的 Bean, 但没有 reqired 属性
建议使用 @Autowired 注解

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

9-组件扫描(注解开发) 的相关文章

随机推荐

  • 小程序无法获取头像和昵称(已解决)

    从基础库 2 21 2 开始支持 当小程序需要让用户完善个人资料时 可以通过微信提供的头像昵称填写能力快速完善 根据相关法律法规 为确保信息安全 由用户上传的图片 昵称等信息微信侧将进行安全检测 组件从基础库2 24 4版本起 已接入内容安
  • Python+Selenium+phantomjs实现网页模拟登录和截图

    Python Selenium phantomjs实现网页模拟登录和截图 本文全部操作均在windows环境下 安装 Python Python是一种跨平台的计算机程序设计语言 它可以运行在Windows Mac和各种Linux Unix系
  • C++ Primer 学习笔记 第十章 泛型算法

    标准库容器很小 并未给每个容器添加大量功能 而是提供了一组算法 这些算法大多数都独立于任何特定的容器 这些算法是通用的 或者说是泛型的 generic 可用于不同类型容器和元素 大多数泛型算法定义在头文件algorithm中 头文件numb
  • Linux 用户管理

    一 useradd命令 创建普通用户的 语法 c lt 备注 gt 加上备注文字 备注文字会保存在passwd的备注栏位中 d lt 登入目录 gt 指定用户登入时的启始目录 D 变更预设值 e lt 有效期限 gt 指定帐号的有效期限 f
  • ETL工具——kettle实现简单的数据迁移

    文章目录 1 Kettle概念 2 安装与启动 3 常用组件 4 具体案例 4 1 数据库连接 3 2 sql脚本 3 3 表输入 3 4 字段选择 3 5 表输出 1 Kettle概念 Kettle是一款国外开源的ETL工具 纯java编
  • pnPm——比npm&yarn更胜一筹的包管理器

    官网 Fast disk space efficient package manager pnpm 安装 在 POSIX 系统上 即使没有安装 Node js 也可以使用以下脚本安装 pnpm curl fsSL https get pnp
  • 常用的编译器(不限制编程语言、不限制平台)

    在提到这个问题之前我们应该了解编译器是什么 简单来说 编译器就是将一种语言 通常为高级语言 翻译为另一种语言 通常为低级语言 的程序 一个现代编译器的主要流程有 源代码 gt 预处理器 gt 编译器 gt 目标代码 gt 链接器 gt 可执
  • Spring Cloud Hystrix

    服务容错保护 Spring Cloud Hystrix 在微服务的架构中 存在着很多的服务单元 若一个单元出现故障 就很容易因依赖关系而引发故障蔓延 最终导致整个系统瘫痪 这样的架构相较传统的架构更加不稳定 为了解决这样的问题 产生了断路器
  • Java IO流(FileReader,FileWriter)讲解

    FileReader和FileWriter类是用来读取 写入字符文件的便捷类 使用FileReader FileWriter 可以实现文本文件的复制 对于非文本文件 视频文件 音频文件 图片 只能使用字节流 字符输入流 FileReader
  • Linux脚本练习之script061-输出7的倍数

    script061 题目 题目来源于 SHELL3 输出7的倍数 写一个 bash 脚本以输出数字 0 到 500 中 7 的倍数 0 7 14 21 的命令 脚本一 seq 命令可以输出数字序列 请参考 Linux命令之产生序列化数seq
  • linux之sed用法

    sed是一个很好的文件处理工具 本身是一个管道命令 主要是以行为单位进行处理 可以将数据行进行替换 删除 新增 选取等特定工作 下面先了解一下sed的用法 sed命令行格式为 sed nefri command 输入文本 常用选项 n 使用
  • datagridview数据清空

    处理关于datagridview数据清空问题 尝试后总结 1 程序dt值为空 DataTable dt DataTable dataGridView1 DataSource dt Rows Clear dataGridView1 DataS
  • redis中hashtable 的 rehash/ resizing 策略

    依赖于连续存储的数据结构 具体的 就是依赖array 都有一个resizing问题 对于vector 一般的策略就是满的时候double and copy 降到1 4时候 halve and copy Hashtable也可以这么做 均摊的
  • cloudify学习小结

    参考 http docs getcloudify org 3 4 0 installation from packages http docs getcloudify org 3 4 0 manager bootstrapping clou
  • 【财富空间】卡耐基梅隆首席科学家大卫·伯恩:机器人学与商业机遇

    本文转载自中国人工智能学会 ID CAAI 1981 2017年12月11日 国际知名机器人专家 美国卡耐基梅隆大学机器人研究所所长马歇尔 赫伯特 Martial Hebert 教授和首席科学家大卫 伯恩 David Bourne 教授访问
  • 用animation实现弹框或图片的淡入淡出效果

    CSS部分 skin modal body dl float left padding 5px animation skin 2s keyframes skin 0 opacity 0 25 opacity 0 5 50 opacity 1
  • CCF-CSP 202206-3 角色授权 Java满分题解

    严格按照题意模拟 User类type字段表示用户 用户组 使用一个Map存User所对应的role列表先实现通过role来鉴权 再遍历role列表即可 import java util class Role String roleName
  • mysql之常见函数(单行函数)09

    1 常见函数 单行函数 进阶4 常见函数 这里代表单行函数 概念 类似于java的方法 将一组逻辑语句封装在方法体中 对外暴露方法名 好处 1 隐藏了实现细节 2 提高代码的重用性 调用 select 函数名 实参列表 from 表 特点
  • MFC中实现用DC画线

    void CDrawView OnLButtonDown UINT nFlags CPoint point TODO Add your message handler code here and or call default Messag
  • 9-组件扫描(注解开发)

    组件扫描 component scanning Spring 能够从 classpath 下自动扫描 侦测和实例化具有特定注解的组件 特定组件包括 Component 基本注解 标识了一个受 Spring 管理的组件 Respository