@ImportResource() annotation (injection into spring configuration file)
-
The @ImportResource annotation is used to import Spring configuration files to make the contents of the configuration files take effect; (that is, springmvc.xml and applicationContext.xml written before )
-
There is no Spring configuration file in Spring Boot, and the configuration file we wrote ourselves cannot be automatically recognized;
-
If you want Spring's configuration file to take effect, load it in; @ImportResource is marked on a configuration class.
-
Notice! This annotation is placed on the class of the main entry function, not on the test class
-
Without the @ImportResource() annotation, the program cannot load our spring configuration file at all, so we need to load the spring configuration file into the container.
-
-
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>