@ImportResource()注解的使用

x33g5p2x  于2021-12-14 转载在 其他  
字(2.0k)|赞(0)|评价(0)|浏览(243)

@ImportResource注解用于导入Spring的配置文件,让配置文件里面的内容生效;(就是以前写的springmvc.xml、applicationContext.xml)
Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;
想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上。
注意!这个注解是放在主入口函数的类上,而不是测试类上

不使用@ImportResource()注解,程序根本不能对我们spring的配置文件进行加载,所以我们需要将spring配置文件加载到容器里。

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

}
<?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>

相关文章

微信公众号

最新文章

更多