Spring引入外部配置文件


基于XML引入外部配置文件

直接配置数据库连接信息



 
 
 
 

使用外部配置文件配置数据库信息

创建外部属性配置文件:classpath:db.properties:

db.driverclass=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/userDb?characterEncoding=utf-8
db.username=root
db.password=root

把外部 properties 属性文件引入到 spring 配置文件中:


     
    
    
         
	

    
    

    
    
         
         
         
         
    


基于注解@PropertySource引入配置文件

创建配置文件

创建属性配置文件 classpath:person.properties:

person.name=zhaoyun
person.age= 220
person.mobile=10010

在Java 配置类中引入配置文件

package com.haan.springdemo.annotation.propertiesassigning;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Map;

@Configuration
@PropertySource(value = {"classpath:/person.properties"})
public class MyApplication {
    
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyApplication.class);

//        获取环境变量中配置文件中的key/value
        System.out.println("读取配置文件导入的环境变量key/value=======");
        ConfigurableEnvironment environment = applicationContext.getEnvironment();

        String personName = environment.getProperty("person.name");
        System.out.println(personName);
        String personAge = environment.getProperty("person.age");
        System.out.println(personAge);
        String personMobile = environment.getProperty("person.mobile");
        System.out.println(personMobile);

    }
}