当前位置:首页 > 行业动态 > 正文

spring如何加载配置文件

Spring框架可以通过以下方式加载配置文件:1. 默认加载 bootstrap.properties 或者 bootstrap.yml 这两个配置文件(这两个优先级最高);2. 接着会加载 application.properties 或 application.yml ;3. 如果何配置了 spring.profiles 这个变量,同时还会加载对应的 application- {profile}.properties 或者 application- {profile}.yml 文件, profile 为对应的环境变量,dev ,如果没有配置,则会加载 profile=default 的配置文件。

什么是外部配置文件?

外部配置文件是指在应用程序运行时,可以通过某种方式加载到内存中的配置信息,这些配置信息可以是应用程序的参数设置、数据库连接信息、第三方库的路径等,通过外部配置文件,可以让应用程序在不修改代码的情况下,方便地调整配置信息,提高开发和维护的效率。

Spring框架如何加载外部配置文件?

Spring框架提供了多种方式来加载外部配置文件,主要包括以下几种:

1、基于XML的配置文件

2、基于Java的配置类

3、基于注解的配置

4、使用PropertyPlaceholderConfigurer加载属性文件

spring如何加载配置文件

5、使用Environment对象加载外部配置文件

下面我们分别介绍这几种方式:

1. 基于XML的配置文件

在Spring框架中,可以使用XML文件来定义外部配置信息,我们可以创建一个名为applicationContext.xml的文件,内容如下:

spring如何加载配置文件

<?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="userService" class="com.example.UserServiceImpl"/>
</beans> 

在应用程序启动时,可以通过ClassPathXmlApplicationContextFileSystemXmlApplicationContext类的load()方法加载这个XML文件:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userService"); 

2. 基于Java的配置类

除了XML文件外,我们还可以使用Java类来定义外部配置信息,我们需要创建一个带有@Configuration注解的Java类,并在该类中定义需要的Bean:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        return new UserServiceImpl();
    }
} 

在应用程序启动时,可以通过AnnotationConfigApplicationContext类的register()方法注册这个配置类:

spring如何加载配置文件

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = (UserService) context.getBean("userService"); 

3. 基于注解的配置

除了XML和Java类之外,我们还可以使用注解来定义外部配置信息,我们可以在需要注入Bean的方法上添加@Autowired注解:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UserController {
    @Autowired
    private UserService userService;
} 

在这个例子中,当Spring容器启动时,会自动扫描带有@Component@Service@Repository@Controller等注解的类,并将这些类实例化为Bean,Spring会根据类型匹配和依赖注入的规则,将这些Bean注入到需要的地方,这种方式的优点是简单易用,不需要额外编写XML或Java类,它不能覆盖默认的Bean定义,如果有多个相同类型的Bean存在,可能会导致歧义,这种方式适用于简单的场景。