Spring注解解析之@ImportResource代码实例

作者:袖梨 2022-06-29

本篇文章小编给大家分享一下Spring注解解析之@ImportResource代码实例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

一、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:



    
    

    
    

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了。

相关文章

精彩推荐