基于注解管理bean

news/2025/2/15 14:10:24/

文章目录

  • 一、标记与扫描
    • 1、标记
    • 2、扫描
    • 组件的beanName
  • 二、自动装配
  • 三、纯注解开发模式
        • 1、创建配置类(SpringConfig)
        • 2、加载配置类
        • 3、测试
        • 加载第三方配置文件.properties
        • 使用@Bean配置第三方Bean
  • 四、bean的作用范围与生命周期管理

一、标记与扫描

1、标记

①使用@Component注解标记的普通组件
②使用@Controller注解标记的控制器组件
③使用@Service注解标记的业务逻辑组件
④使用@Repository注解标记的持久化层组件

@Controller、@Service、@Repository这三个注解只是在@Component注解的基础上起了三个新的名字。
对于Spring使用IOC容器管理这些组件来说没有区别。所以@Controller、@Service、@Repository这三个注解只是给开发人员看的,让我们能够便于分辨组件的作用。
注意:虽然它们本质上一样,但是为了代码的可读性,为了程序结构严谨我们肯定不能随便胡乱标记。

2、扫描

①情况一:最基本的扫描方式[常用]

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

②情况二:指定匹配模式
这种模式只会扫描com.iflytek下的文件,不会扫描子包

    <context:component-scan base-package="com.iflytek" resource-pattern="Book*.class"></context:component-scan>

③情况三:指定要排除的组件
排除了使用@Controller注解注入的bean

    <context:component-scan base-package="com.iflytek"><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan>

④情况四:仅扫描指定组件

<!-- 仅扫描 = 关闭默认规则 + 追加规则 -->
<!-- use-default-filters属性:取值false表示关闭默认扫描规则 --><context:component-scan base-package="com.iflytek" use-default-filters="false"><!-- 只注入使用@Controller注解注入的bean --><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan>

组件的beanName

在我们使用XML方式管理bean的时候,每个bean都有一个唯一标识,便于在其他地方引用。现在使用注解后,每个组件仍然应该有一个唯一标识。

①默认情况
类名首字母小写就是bean的id。例如:SoldierController类对应的bean的id就是soldierController。
②使用value属性指定
eg:@Controller(value = (“bookController”))

二、自动装配

@Autowired:先根据类型装配,如果有多个相同类型的bean,再根据id装配

@Qualifier:指定名称,按照名称来查找,通常和@Autowired注解搭配使用

@Resource:默认按照名称自动装配,如果名称找不到的话,就按照类型动装配

1.定义一个service接口和两个实现类

public interface BookService {void getBook();
}
@Service
public class BookServiceImpl implements BookService {@Overridepublic void getBook() {System.out.println("获取书本");}
}
@Service
public class BookServiceImpl2 implements BookService {@Overridepublic void getBook() {System.out.println("获取书本2");}
}

2、在BookController中注入这个BookService

@Controller
public class BookController {@Autowiredprivate BookService bookService;public void getBook(){bookService.getBook();
}}

这里肯定是注入失败的,因为有两个BookService的实现类

解决办法:① @Autowired+@Qualifie注解

@Controller
public class BookController {@Autowired@Qualifier(value = "bookServiceImpl2")private BookService bookService;public void getBook(){bookService.getBook();
}}

②修改其中一个Service的id

@Service(value = "bookService")
public class BookServiceImpl implements BookService {@Overridepublic void getBook() {System.out.println("获取书本");}
}
@Service(value = "bookService2")
public class BookServiceImpl2 implements BookService {@Overridepublic void getBook() {System.out.println("获取书本2");}
}

@Autowired注解其他细节
①标记在其他位置
[1]构造器

@Controller(value = "tianDog")
public class SoldierController {private SoldierService soldierService;@Autowiredpublic SoldierController(SoldierService soldierService) {this.soldierService = soldierService;}

[2]setXxx()方法

@Controller(value = "tianDog")
public class SoldierController {private SoldierService soldierService;@Autowiredpublic void setSoldierService(SoldierService soldierService) {this.soldierService = soldierService;}

②@Autowired工作流程
在这里插入图片描述

三、纯注解开发模式

没有配置文件ApplicationContext.xml文件

1、创建配置类(SpringConfig)

等同于ApplicationContext.xml文件

@Configuration
@ComponentScan("com.itheima.service.impl")
public class SpringConfig {}

使用@Configuration注解消除配置文件中的下面这段代码

image-20220717154439080

使用@ComponentScan消除消除配置文件中的下面这段代码

image-20220717163801262

@Configuration注解用于设定当前类为配置类

@ComponentScan注解用于设定扫描路径,此注解只能添加一次,多个数据请用数组格式

2、加载配置类

使用配置文件时:

  ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");

使用纯注解开发后:

ApplicationContext ctx=new AnnotationConfigApplicationContext(SpringConfig.class);
3、测试
public static void main(String[] args) {ApplicationContext applicationContext=new AnnotationConfigApplicationContext(SpringConfig.class);BookService bean = applicationContext.getBean(BookService.class);bean.save();
}
加载第三方配置文件.properties

使用@PropertySource

在配置类中

image-20220717162018991
使用占位符设置对应的值
image-20220717162051636

如果要加载多个Properties文件

设置为集合的格式

@PropertySource({"jdbc2.properties"})
使用@Bean配置第三方Bean

并且不要写在SpringCongfig配置类中

创建一个JdbcConfig类

public class JdbcConfig {//1.定义一个方法获得要管理的对象//2.添加@Bean,表示当前方法的返回值是一个bean@Beanpublic DataSource dataSource(){DruidDataSource ds=new DruidDataSource();ds.setDriverClassName("com.mysql.jdbc.Driver");ds.setUrl("jdbc:mysql://localhost:3306/spring_db");ds.setUsername("root");ds.setPassword("20020630");return ds;}}

在配置类SpringConfig类中使用@Import导入这个类

@Configuration
@Import(JdbcConfig.class)
public class SpringConfig {}

四、bean的作用范围与生命周期管理

@Scope(“singleton”)单例模式

@Scope(“prototype”)非单例模式

生命周期:

@PostConstruct初始化

@PreDestroy销毁

注意:使用JDK11需要导入依赖坐标

<dependency><groupId>javax.annotation</groupId><artifactId>javax.annotation-api</artifactId><version>1.3.2</version>
</dependency>

使用举例:

@Componentpublic class BookServiceImpl implements BookService {public void save() {System.out.println("BookService!");}@PostConstructpublic void init(){System.out.println("初始化");}@PreDestroypublic void destory(){System.out.println("销毁前");}
}

http://www.ppmy.cn/news/1357064.html

相关文章

prometheus+mysql_exporter监控mysql

prometheusmysql_exporter监控mysql 一.安装mysql 1.下载&#xff1a;wget -i -c http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm 2.安装客户端&#xff1a;yum -y install mysql57-community-release-el7-10.noarch.rpm 3.安装服务端&#xff1a;yum …

极狐GitLab 如何配置多个 LDAP?

本文仅适用于极狐GitLab私有化部署场景。 场景化痛点 极狐GitLab 的多 LDAP 接入功能解决了企业在以下场景中可能遇到的痛点&#xff1a; 多个组织/部门的整合&#xff1a;在大型企业或跨国公司中&#xff0c;往往存在多个组织或部门&#xff0c;它们可能拥有独立的 LDAP 服务…

C语言——从头开始——深入理解指针(1)

一.内存和地址 我们知道计算上CPU&#xff08;中央处理器&#xff09;在处理数据的时候&#xff0c;是通过地址总线把需要的数据从内存中读取的&#xff0c;后通过数据总线把处理后的数据放回内存中。如下图所示&#xff1a; 计算机把内存划分为⼀个个的内存单元&#xff0c;每…

【selenium】

selenium是一个Web的自动化测试工具&#xff0c;最初是为网站自动化测试而开发的。Selenium可以直接调用浏览器&#xff0c;它支持所有主流的浏览器。其本质是通过驱动浏览器&#xff0c;完成模拟浏览器操作&#xff0c;比如挑战&#xff0c;输入&#xff0c;点击等。 下载与打…

如何在CentOS安装SQL Server数据库并实现无公网ip环境远程连接

文章目录 前言1. 安装sql server2. 局域网测试连接3. 安装cpolar内网穿透4. 将sqlserver映射到公网5. 公网远程连接6.固定连接公网地址7.使用固定公网地址连接 前言 简单几步实现在Linux centos环境下安装部署sql server数据库&#xff0c;并结合cpolar内网穿透工具&#xff0…

LeetCode 算法题 (数组)存在连续3个奇数的数组

问题&#xff1a; 输入一个数组&#xff0c;并输入长度&#xff0c;判断数组中是否存在连续3个元素都是奇数的情况&#xff0c;如果存在返回存在连续3个元素都是奇数的情况&#xff0c;不存在返回不存在连续3个元素都是奇数的情况 例一&#xff1a; 输入&#xff1a;a[1,2,3…

vue3使用pinia

vue3使用pinia pinia类似于vuex, 但相对于vuex少了mutations和modules。 vuex: 集中式管理状态容器, 可以实现任意组件之间通信; 核心概念: state\mutations\actions\getter\modules。 pinia: 集中式管理状态容器, 可以实现任意组件之间通信 核心概念: state\actions\getters。…

08MARL深度强化学习——模型种类

文章目录 前言1、训练与执行的模型2、Centralised Training and Execution2.1 Example——central learning2.2 局限性 3、Decentralised Training and Execution3.1 Example——independent learning3.2局限性 4、Centralised Training with Decentralised Execution4.1 Examp…