Spring boot导入Spring配置(Java学习笔记)

默认情况下,Spring Boot 中是不包含任何的 Spring 配置文件的,即使我们手动添加 Spring 配置文件到项目中,也不会被识别。那么 Spring Boot 项目中真的就无法导入 Spring 配置吗?答案是否定的。

Spring Boot 为了我们提供了以下 2 种方式来导入 Spring 配置:

使用 @ImportResource 注解加载 Spring 配置文件
使用全注解方式加载 Spring 配置

@ImportResource 导入 Spring 配置文件

在主启动类上使用 @ImportResource 注解可以导入一个或多个 Spring 配置文件,并使其中的内容生效。

  1. 主程序添加spring的配置文件路径
@ImportResource(locations={"classpath:beans.xml"}) 
  1. 编写beans.xml配置文件
<?xmlversion="1.0"encoding="UTF‐8"?>
<beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring‐beans.xsd">

    <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>

全注解方式加载 Spring 配置

Spring Boot 推荐我们使用全注解的方式加载 Spring 配置,其实现方式如下:

/**
 * @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
 */
@Configuration
publicclassMyAppConfig{
//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名 
@Bean
public HelloService helloService02(){
System.out.println("配置类@Bean给容器中添加组件了...");
        return new HelloService();
    }

使用 @Configuration 注解定义配置类,替换 Spring 的配置文件;
配置类内部可以包含有一个或多个被 @Bean 注解的方法,这些方法会被 AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext 类扫描,构建 bean 定义(相当于 Spring 配置文件中的标签),方法的返回值会以组件的形式添加到容器中,组件的 id 就是方法名。

学习原文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值