微人事第四天:springboot中使用xml配置

在springboot中也可以使用xml配置,接下来通过一个例子来演示一下:
1.创建一个实体类

package org.javaboy.xml;


public class SayHello {

    public String sayHello() {
        return "hello xml";
    }
}

2.bean.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 class="org.javaboy.xml.SayHello" id="sayHello"/>
</beans>

3.配置类

package org.javaboy.xml;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource(locations = "classpath:bean.xml")
public class WebMvcConfig {

}

这里的@ImportResource用于将bean.xml文件中的bean加载到Application Context中。locations代表是xml文件的位置。

4.测试类

package org.javaboy.xml;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class XmlApplicationTests {

    @Autowired
    private SayHello sayHello;

    @Test
    void contextLoads() {
        System.out.println(sayHello.sayHello());
    }

}

打印结果:

hello xml

由于之前的@ImportResource,我们已经将配置的bean加载进来了,而bane中配置的是SayHello这个类,所以这里可以把测试类注入进来。

另一种简单的做法就是直接在实体类上加上@Configuration,这和xml中配置bean的效果是一样的。

发布了287 篇原创文章 · 获赞 24 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41998938/article/details/104017586
今日推荐