<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" > <!--加載配置文件能夠支持,分割同時加載多個配置文件--> <context:property-placeholder location="classpath:db.properties"/> <!--註解掃描器--> <context:component-scan base-package="com.suncl"></context:component-scan> </beans>
db.url=127.0.0.1/dev db.username=zhangsan db.pwd=1123456
package com.suncl.model; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * Created by SCL-PC on 2019/3/5. */ @Component public class DbConfig { @Value("${db.url}") private String url; @Value("${db.username}") private String username; @Value("${db.pwd}") private String pwd; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "DbConfig{" + "url='" + url + '\'' + ", username='" + username + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
package com.suncl.test; import com.suncl.model.DbConfig; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by SCL-PC on 2019/2/28. */ public class Test { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); DbConfig dbConfig = (DbConfig)ac.getBean("dbConfig",DbConfig.class); System.out.println(dbConfig.toString()); } }
信息: Loading properties file from class path resource [db.properties] DbConfig{url='127.0.0.1/dev', username='zhangsan', pwd='1123456'}
以上就是spring加載配置文件的內容。 連接:https://pan.baidu.com/s/1mmaMcaXEqLjYbipzpLo42Q 提取碼:jl0l spring