SpringBoot学习(三)-----使用@ImportResource引入SpringBean.xml

我们可以使用注解@ImportResource引入SpringBean.xml

首先建立一个SpringBoot,添加SpringBootApp.java、beans.xml、HelloService.java、SpringBoottest.java如下:

HelloService.java

package com.zk.service;

public class HelloService {

}

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="HelloService" class="com.zk.service.HelloService"></bean>
</beans>

SpringBootApp.java

package com.zk.myspringboot005Controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource(locations={"classpath:beans.xml"})
//@ImportResource:导入spring配置文件让配置文件的内容生效
public class SpringBootApp{

	public static void main(String[]args){
		SpringApplication.run(SpringBootApp.class, args);
	}
}

SpringBoottest.java

package com.zk.myspringboottest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;

import com.zk.myspringboot005Controller.SpringBootApp;
import com.zk.service.HelloService;

@RunWith(SpringRunner.class)
@SpringBootTest(classes={SpringBootApp.class})
@Import(HelloService.class)
public class SpringBoottest {
	
	@Autowired
	private ConfigurableApplicationContext ioc;
	
	HelloService helloservice;
	
	@Test
	public void testHelloService(){
		System.out.println(ioc.containsBean("HelloService"));
	}
	
}

 运行SpringBoottest.class,运行结果如下:

 这里需要注意,使用@ImportResource引入bean.xml

//@ImportResource:导入spring配置文件让配置文件的内容生效
@ImportResource(locations={"classpath:beans.xml"})

  

猜你喜欢

转载自www.cnblogs.com/longlyseul/p/12497788.html