Spring/SpringBoot中引入xml的Spring配置文件

使用注解+配置类方式引入配置文件

在Spring中,我们经常使用xml的配置文件去将Java对象交给Spring容器进行管理。然后在编写类似如下的测试类,那么我们应该如何去将xml配置文件自动导入全局呢?请接着看下面

//1.指定配置文件
String config = "beans.xml";
//2.创建表示Spring容器的对象,ApplicationContext
//ApplicationContext就表示Spring容器。
//ClassPathXmlApplicationContext表示从类路径加载配置文件,类似的还有一个从文件系统加载配置文件的类(一般不使用)
ApplicationContext ac = new ClassPathXmlApplicationContext();

//3.从容器中获取对象
Object o = ac.getBean("bean_id");  //参数是id,返回值是object,使用时要进行拆箱

//4.使用spring创建好的对象(先拆箱)直接调用对应的方法。

//说明:在以后我们不使用这么复杂的操作
//使用同一个java类,可以创建多个不同的java对象
//通过不同的id就可以创建出来不同的对象
//默认调用的是无参数的构造函数

我们也可以使用注解的方式,避免了每次都要指定配置文件的路径,还得获取Context的方式。

编写Bean

package com.example.demopro.bean;

public class ProductBean {
    int id;
    String productName;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    @Override
    public String toString() {
        return "ProductBean{" +
                "id=" + id +
                ", productName='" + productName + '\'' +
                '}';
    }
}

编写配置文件,resource/config/product.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="product1" class="com.example.demopro.bean.ProductBean">
        <property name="id" value="1"></property>
        <property name="productName" value="wanna"></property>
    </bean>


</beans>

编写配置类,使用@Configuration注解,并使用@ImportResource注解指定需要扫描的配置文件,这样他就能自动加入SpringContext。

package com.example.demopro.config;

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

@Configuration
@ImportResource(value = "classpath:config/*.xml")
public class TestConfig {
}

这样,就能将配置文件加载到全局的Context,将ProdcuctBean交给Spring去管理。<br />
编写测试类,使用自动注入的方式将Bean注入ProductBean对象

package com.example.demopro;

import com.example.demopro.bean.ProductBean;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SpringBootTest
class DemoproApplicationTests {
    @Autowired
    ProductBean productBean;

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

    }

}

测试成功!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容