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

本文介绍了如何使用Spring框架中的注解如@Configuration、@ComponentScan、@PropertySource和@Import来替代XML配置文件,包括组件扫描、属性加载和导入其他配置类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"));
          }
      }
      
      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值