@ImportResource注解详解大全
下文笔者讲述@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中的内容
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。