当前位置: 首页 > news >正文

Spring的注解开发-Spring配置类的开发

Bean配置类的注解开发

  • @Component等注解替代了<bean>标签,但像<import>、<context:componentScan>等非<bean>标签怎样去使用注解去替代呢?定义一个配置类替代原有的xml配置文件,<bean>标签以外的标签,一般都是在配置类上使用注解完成的
  • @Configuration注解标识的类为配置类,替代原有的xml配置文件,该注解的第一个作用是标识该类是一个配置类,第二个作用是具备@Component注解的作用,将该配置类交给Spring容器管理
  • @ComponentScan组件扫描配置,替代原有的xml文件中的<context:component-scan base-package=""/>
    • base-package的配置方式
    • 指定一个或者多个包名:扫描指定包及其子包下使用的注解类
    • 不配置包名:扫描当前@ComponentScan注解配置类所在包及其子包的类
  • @PropertySource注解用于加载外部properties资源配置,替代原有xml文件中的 <context:property-placeholder location=""/>配置
  • @Import用于加载其它配置类,替代原有xml中的<import resource="classpath:bean.xml"/>配置
  • 具体示例代码如下
    • package com.example.Configure;import com.example.Beans.otherBeans;
      import org.springframework.context.annotation.ComponentScan;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.context.annotation.Import;
      import org.springframework.context.annotation.PropertySource;@Configuration // todo 标注当前类是一个配置类(替代配置文件)、其中包含@Compoent注解
      // <context:component-scan base-package="com.example"/>
      @ComponentScan({"com.example"})
      // <context:property-placeholder location="jdbc.properties"/>
      @PropertySource("jdbc.properties")
      // <import resource=""/>
      @Import(otherBeans.class)
      public class SpringConfig {}
      

小结

  • 创建配置类作用其实就是用来替代配置文件的作用,xml配置文件中的不同标签都在配置类中用对应的注解进行替代,由此获取Spring容器的方式也会发生变化,由之前的xml方式获取Spring核心容器变为通过注解的方式加载Spring容器的核心配置类。
    • package com.example.Test;import com.example.Configure.SpringConfig;
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestApplicationContext {public static void main(String[] args) {// xml方式加载Spring容器的核心配置文件// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");// 注解方式加载Spring容器的核心配置类ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);System.out.println(context.getBean("dataSource"));}
      }

http://www.lryc.cn/news/179780.html

相关文章:

  • Linux系统编程系列之进程间通信-信号量组
  • centos 6使用yum安装软件
  • maven无法下载时的解决方法——笔记
  • Java Spring Boot 开发框架
  • Pytorch学习记录-1-张量
  • paddle2.3-基于联邦学习实现FedAVg算法-CNN
  • nuiapp保存canvas绘图
  • Object.defineProperty()方法详解,了解vue2的数据代理
  • Linux 磁盘管理
  • 大数据与人工智能的未来已来
  • 【AI视野·今日Robot 机器人论文速览 第四十一期】Tue, 26 Sep 2023
  • [NOIP2012 提高组] 开车旅行
  • 数据库设计流程---以案例熟悉
  • Miniconda创建paddlepaddle环境
  • postgresql实现单主单从
  • 提取PDF数据:Documents for PDF ( GcPdf )
  • adb连接切换到模拟器端口
  • 为何每个开发者都在谈论Go?
  • 【Leetcode】 501. 二叉搜索树中的众数
  • 怎样给Ubuntu系统安装vmware-tools
  • DDS信号发生器波形发生器VHDL
  • Python3操作SQLite3创建表主键自增长|CRUD基本操作
  • B. Comparison String
  • python端口扫描
  • 国庆第二天
  • Java安全之servlet内存马分析
  • 2023年第二十届中国研究生数学建模竞赛总结与分享
  • Web前端-Vue2+Vue3基础入门到实战项目-Day1(初始Vue, Vue指令, 小黑记事本)
  • Sentinel学习(2)——sentinel的使用,引入依赖和配置 对消费者进行流控 对生产者进行熔断降级
  • springboot 简单配置mongodb多数据源