Spring框架可以通過(guò)以下方式加載配置文件:1. 默認加載 bootstrap.properties 或者 bootstrap.ym(°ロ°) !l 這兩個(gè)配置文件(這兩個(gè)優(yōu)先級最高);2. 接著(zhù)會(huì )加載 application.properties 或 applica?tion.yml ;3. 如果何配置了 spring.profiles 這個(gè)變(bian)量,何加同時(shí)還會(huì )加載對應的載配置文(╯°□°)╯︵ ┻━┻ application- { profile}.properties 或者 application- { profile}.yml┐(′?`)┌ 文件, profile 為對應的何加環(huán)境變量,d??ev ,載配置文如果沒(méi)有配置,則會(huì )加載 profile=default 的何加配置文件。
外部配置文件是指在應用程序運行時(shí)(shi),可以通過(guò)某種方式加載到內存中的何加配置信息,這些配置信息可以是載配置文應用程??(??-)?序的參數設置、數據庫連接信息、何加第三方庫的載配置文路徑等,通過(guò)外部配置文件,何加可以讓?xiě)贸绦蛟诓恍薷拇a的載配置??文情況下,方便地調??(diao)整配置信息,何加提高開(kāi)發(fā)和維護的載配置文效率。
Spring框架提供了多種方式來(lái)加載外部配置文件,主要包括以下幾種:
1、基于XML的配置文件
3、基于注解的配置
4、使用PropertyPlaceholderConfigurer加載屬性文??件
5、使用Environment對象加載外部配置文件
下面我們分別介紹這幾種方式??:
1. 基于XML的配置文件
在Spring框架中,可以使用XML文件來(lái)定義外部配置信息,我們可以創(chuàng )建一個(gè)名為applicationContext.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.spring?framework.org/schema/beans/spring-be??ans.xsd"> <bean id="userService" class="com.example.UserServiceImpl"/></beans&g??t;
在應用程序啟動(dòng)時(shí),可以通過(guò)Clas( ?ヮ?)sPathXmlApplicationCo(╬?益?)ntext或FileSystemXmlApplicationContext類(lèi)的load()方法加載這個(gè)XML文件:
ApplicationContext context = new ClassPathX??mlApplicationContext("applicationContext.xml&q??uot;);UserService userService = (UserService(⊙_⊙)) context.getBean("userService");2. 基于Java的配置類(lèi)
除了XML文件外,我們還可以使用Java類(lèi)來(lái)定義外部配置信息,我們需要創(chuàng )建一個(gè)帶有@Conf???(′Д` )iguration注解的Java類(lèi),并在該類(lèi)中定義需要的Bean:
import org.s??pringframework.context.annotation.Bean(′?_?`);import org.s(′;ω;`)pringframework.context.annot(′_`)ation.Configuration;@Configurationpublic class AppConfig { @Be??an public UserService userService() { return new Us??erServiceImpl(); }}在應用程序啟動(dòng)時(shí),可以通過(guò)Anno??tationConfigApplicationContext類(lèi)的register()方法注冊這個(gè)配置類(lèi):
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);UserService userService = (UserService) context.getBean("userService&quヾ(′▽?zhuān)??ot;);3. 基于注(?Д?)解的配置
除了XML和Java類(lèi)之外,我們還可以使用注解來(lái)定義??外部配置信息,我們可以在需要注入Bean的方法上添加@Autowired注解:
import org.springframework.beans.fa??ctory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class UserController { @Autowired private UserService userService;}在這個(gè)例子中,當Spring容器啟動(dòng)時(shí),會(huì )自動(dòng)掃描帶ヾ(′ω`)?有@Component、@Service、@Rep??ository或@Controller等注解的類(lèi),并將這些類(lèi)實(shí)例化為Bean,Spring會(huì )根據類(lèi)型匹配和依賴(lài)注入的規則,將這些Bean注入到需要的地方,這種方式的優(yōu)點(diǎn)是簡(jiǎn)單易用,不需要額外編寫(xiě)XML或Java類(lèi),它不能覆蓋默認的Bean定義,如果有多個(gè)相同類(lèi)型的Bean存在,可能會(huì )導致歧義,這種方式適用于簡(jiǎn)單的場(chǎng)景。
(作者:百度SEO工具)