欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

@ImportResource()注解的使用

发布时间:2025/3/12 编程问答 24 豆豆
生活随笔 收集整理的这篇文章主要介绍了 @ImportResource()注解的使用 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

@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 {@AutowiredApplicationContext applicationContext;@Testvoid 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>

总结

以上是生活随笔为你收集整理的@ImportResource()注解的使用的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。