之前说过,Spring Boot推荐使用注解,那为什么这里还需要介绍通过xml来配置bean的方法呢,因为一些第三方的组件是基于spring的xml配置来进行开发的,比如阿里巴巴的dubbo框架,所以如果要使用这些框架,那便只能使用xml的方式来配置对应的bean了。使用@ImportResource注解,Spring Boot便可以使用xml配置bean了,下面让我们一起来看看。
@ImportResource注解
该注解用于告诉Spring从哪个xml配置文件中读取bean的配置信息。
首先我们创建一个类,计划将其交由Spring管理,代码如下:
@Slf4j
public class Squirrel {
public void use(){
log.warn("松鼠可以采集松果......");
}
}
可以看到,我们并没有使用@Component这种注解来标记,所以一般情况下,Spring是不会扫描到该bean的。
接下来我们在resource文件夹下面创建一个spring-other.xml配置文件,用来配置Squirrel 的信息,代码如下:
<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="squirrel" class="com.zzm.xmlbeantest.bean.Squirrel"/>
</beans>
然后创建容器的配置类,指定从该xml文件中读取bean的配置信息:
@ImportResource(value = {"classpath:spring-other.xml"})
@ComponentScan(basePackages = {"com.zzm.xmlbeantest"})
@Configuration
@Slf4j
public class XmlBeanAppConfig {
}
最后创建测试类:
@Slf4j
public class XmlBeanTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(XmlBeanAppConfig.class);
Squirrel squirrel = context.getBean(Squirrel.class);
squirrel.use();
}
}
运行main方法,可以看到Squirrel的实例成功通过xml文件注册到了Spring之中:
好了,今天就先到这里了,眼过千遍不如手过一遍,赶紧去自己尝试一下吧。。。。拜拜