Spring注解解析之@ImportResource
作者:wang0907
一、ImportResource
1.1 定义包和类
首先定义一个不会被ComponentScan
扫描到的包outpackage
,如下:
在该包内创建一个类:
package outpackage; import org.springframework.stereotype.Service; @Service public class HelloService1 { public void method1() { System.out.println("class:HelloService1__method:method1"); } }
1.2 定义配置文件
在资源目录添加配置文件applicationContext.xml
:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 开启注解模式 --> <context:annotation-config/> <!-- 基于注解自动注册spring bean --> <context:component-scan base-package="outpackage"/> </beans>
1.3 定义Java Config类
在启动类平级目录或者是子目录添加java config类保证能够被springboot扫描到
,引入xml配置,如下:
package dongshi.daddy; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource({"classpath:applicationContext.xml"}) public class OuterPackageConfiguration { }
1.4 测试代码
@SpringBootApplication public class HelloWorldMainApplication { public static void main(String[] args) throws URISyntaxException, IOException { ConfigurableApplicationContext run = SpringApplication.run(HelloWorldMainApplication.class, args); // 获取通过配置文件定义而被扫描到的类 HelloService1 bean = run.getBean(HelloService1.class); System.out.println(bean); } }
二、运行
2021-05-19 17:52:52.896 INFO 16232 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8083 (http) with context path ''
...snip...
outpackage.HelloService1@1929425f
为了证明确实是xml配置文件在起作用,而不是springboot自己扫描注册,修改配置类,注释掉@ImportResource({"classpath:applicationContext.xml"})
,如下:
package dongshi.daddy; import org.springframework.context.annotation.Configuration; @Configuration //@ImportResource({"classpath:applicationContext.xml"}) public class OuterPackageConfiguration { }
然后运行:
2021-05-19 18:01:10.522 INFO 18260 --- [ main] dongshi.daddy.HelloWorldMainApplication : Started HelloWorldMainApplication in 0.944 seconds (JVM running for 1.355)
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'outpackage.HelloService1' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1123)
at dongshi.daddy.HelloWorldMainApplication.main(HelloWorldMainApplication.java:16)
可以看到就找不到对应的bean了。
到此这篇关于Spring注解解析之@ImportResource的文章就介绍到这了,更多相关@ImportResource注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!