@ImportResource()注解的使用

1、问题描述

默认情况下,Boot框架没有Spring的配置文件,所编写的配置文件也不能自动识别。此情况下,xml配置是否就真没有用武之地呢?答案是否定的。@ImportResource(location=" ")注解的出现就能解决此问题。

2、作用

  • 该注解用于导入Spring的配置文件,令此配置文件里的内容生效。倘若不使用@ImportResource()注解,程序根本不能对spring配置文件进行加载,故需要将spring配置文件加载到容器里。

3、实例

  • 在相对目录下创建配置文件:applicationContext.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="dog1" class="com.yangzhenxu.firstspringboot.bean.Dog">
        <property name="name" value="zhangxue"/>
        <property name="age" value="27"/>
    </bean>
</beans>
  • 在启动类中通过该注解引入上述配置文件
package com.yangzhenxu.firstspringboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@ImportResource(locations = "classpath:applicationContext.xml")
@SpringBootApplication
@RestController
public class FirstSpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstSpringbootApplication.class, args);
    }
}
  • 测试类
package com.yangzhenxu.firstspringboot;

import com.yangzhenxu.firstspringboot.bean.Person;
import javafx.application.Application;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;


@SpringBootTest
class FirstSpringbootApplicationTests {
    @Autowired
    ApplicationContext applicationContext;
    @Test
    void testapplication() {
        Object a = applicationContext.getBean("dog1");
        System.out.println(a);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值