@ImportResource注解详解大全

乔欣 SpringBoot 发布时间:2023-03-12 21:41:01 阅读数:3311 1
下文笔者讲述@ImportResource注解的功能说明,如下所示

@ImportResource注解的功能

使用@ImportResource实现xml配置的装载 
   @ImportResource:导入Spring的配置文件,让配置文件里面的内容生效
//扫描相关的注解配置类 
@ComponentScan(basePackages={"com.java265.SpringBoot1","com.java265.springboot.*"})

//先定义一个service层bean:
package com.java265.springboot2.service;
import org.springframework.stereotype.Service;

@Service
public class HelloService1 {
public void method1(){
	System.out.println("class:HelloService1__method:method1");
  }
}

//添加xml配置文件applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" default-autowire="byName" default-lazy-init="false" >
<description>Spring Configuration</description>
<!-- 开启注解模式 -->
<context:annotation-config />
<!-- 使用Annotation自动注册Bean -->
<context:component-scan base-package="com.java265.springboot2.service">
</context:component-scan>
</beans>  


//新增一个关键的配置类XmlConfiguration

package com.java265.springboot.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource(locations={"classpath:applicationContext.xml"})
public class XmlConfiguration {

}



@RestController
public class HelloWorldController {
@Autowired
ServerConfig serverConfig;
@Autowired
ServerConfig2 serverConfig2;
@Autowired
HelloService1 helloService1;
@RequestMapping("/")
public String helloWorld() {
System.out.println("server.properties服务器端口:"+serverConfig.getPort());
System.out.println("application.properties服务器端口:"+serverConfig2.getPort());
helloService1.method1();
return "Hello World!";
}
}

//启动程序  即可正常打印service中的内容
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202303/6017.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者