导入Spring配置文件

SpingBoot的配置文件导入

@ImportSource 可以导入Spring配置文件
SpringBoot里面没有Spring的配置文件,我们自己编写文件,也不能自动识别
想让Spring的配置文件生效,加载进来;@ImportSource标注一个配置类上来
创建一个Sprin配置文件 用xml配bean的文件 kk.xml

@ImportResource(locations = {"classpath:kkout.xml"})
先将其放在主配置类里试一下

还需要创建一个Nihao类
该类作用起到与Bean组件相互连接的作用

  1. 方法一:用xml配bean的方式
    创建一个kk.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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="Nihao" class="com.example.funspring.sever.Nihao"></bean>
</beans>

在Test类里进行测试

@Autowired   //该注解为自动导入
ApplicationContext ioc;

@Test
public void contextNihao(){
    boolean b=ioc.containsBean("Nihao");   //该方法可以寻找是否有bean  字符串为Bean组件的id名
    System.out.println(b);

运行控制台返回true,说明Spring配置文件导入到了主类中

  1. 方法二
    推荐Springboot推荐给容器中添加组件的方式 推荐权注解的方式

    配置类 Spring配置文件
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {

    //将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名或类名
    //@bean  注解可以注解到方法上和类上
    @Bean
    public Nihao fun(){
        System.out.println("给容器配bean");
        return new Nihao();
    }
}

记得要将上一个方法的
@ImportResource(locations = {“classpath:kkout.xml”})注解掉

在到test类中测试
发现返回 “给容器配bean”
true
说明配置成功

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值