@ImportResource 注解的理解和使用

Dear 丶 2024-03-31 13:00 242阅读 0赞

通过@ImportResource实现xml配置的装载 @ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;通过初识springboot的实践,所有的bean装载全部通过java配置实现,那么一直以来习惯的xml配置是否就没有了用武之地呢,答案是否定的,下面就通过实践验证说明。

1、通过之前的实践,在启动类APP中定义了

  1. @ComponentScan(basePackages={"com.shf.SpringBoot1","com.shf.springboot.*"})

扫描相关的注解配置类,故本次案例中的bean放置在其他包下,从而通过xml文件注册;

2、首先定义一个service层bean:

  1. package com.shf.springboot2.service;
  2. import org.springframework.stereotype.Service;
  3. @Service
  4. public class HelloService1 {
  5. public void method1(){
  6. System.out.println("class:HelloService1__method:method1");
  7. }
  8. }

3、添加xml配置文件applicationContext.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context.xsd" default-autowire="byName" default-lazy-init="false" >
  9. <description>Spring Configuration</description>
  10. <!-- 开启注解模式 -->
  11. <context:annotation-config />
  12. <!-- 使用Annotation自动注册Bean -->
  13. <context:component-scan base-package="com.shf.springboot2.service">
  14. </context:component-scan>
  15. </beans>

4、下面就是新增一个关键的配置类XmlConfiguration:

  1. package com.shf.springboot.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.context.annotation.ImportResource;
  4. @Configuration
  5. @ImportResource(locations={"classpath:applicationContext.xml"})
  6. public class XmlConfiguration {
  7. }

该配置类此时必须在启动类中扫描到。

5、在控制其中注入2中定义的service对应的bean,并调用其方法:

  1. @RestController
  2. public class HelloWorldController {
  3. @Autowired
  4. ServerConfig serverConfig;
  5. @Autowired
  6. ServerConfig2 serverConfig2;
  7. @Autowired
  8. HelloService1 helloService1;
  9. @RequestMapping("/")
  10. public String helloWorld() {
  11. System.out.println("server.properties服务器端口:"+serverConfig.getPort());
  12. System.out.println("application.properties服务器端口:"+serverConfig2.getPort());
  13. helloService1.method1();
  14. return "Hello World!";
  15. }
  16. }

6、启动程序,验证结果,是否能够正常的打印service中的内容。

  1. ![](https://upload-images.jianshu.io/upload_images/
  2. 4055666-e2ebf663867c30c7.png?imageMogr2/auto-orient/
  3. strip%7CimageView2/2/w/1240)

以上正常装载bean,正常注入bean,正常使用bean实例。本案例主要使用到了一个新的注解: @ImportResource:通过locations属性加载对应的xml配置文件,同时需要配合@Configuration注解一起使用,定义为配置类

发表评论

表情:
评论列表 (有 0 条评论,242人围观)

还没有评论,来说两句吧...

相关阅读