代码已上传至github,感兴趣的可以一起学习交流~
一 通过<context:property-placeholder>标签
<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 配置扫包路径 --> <context:component-scan base-package="com.liyefei.spring.demo" /> <!-- 开启注解 --> <context:annotation-config /> <!-- 加载配置文件 --> <context:property-placeholder ignore-unresolvable="true" location="param1.properties" /> </beans>
如何使用?
- xml中使用
<property name="url" value="${jdbc.url}" />
- java中使用
@Component @Data public class InitParam { @Value("${offline}") private boolean offline; @Value("${domain}") private String domain; }
如何取值?
public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Application.xml"); //方式1:通过<context:property-placeholder>标签 InitParam1 initParam = (InitParam1) context.getBean("initParam1"); System.out.println("method1:" + initParam); }
二 通过@PropertySource注解实现配置文件加载
@PropertySources({@PropertySource(value = "param2.properties")}) public class AppConfig { @Bean public InitParam2 initParam2(){ return new InitParam2(); } }
@Data
public class InitParam2 {
@Value("${param2.offline}")
private String offline;
@Value("${param2.domain}")
private String domain;
}
如何取值?
//方式2:通过@PropertySource注解实现配置文件加载 AnnotationConfigApplicationContext annoContext = new AnnotationConfigApplicationContext(AppConfig.class); //方式2.1 通过getBean方法获取参数 InitParam2 initParam2 = annoContext.getBean(InitParam2.class); System.out.println("method2:" + initParam2);
或者
//方式2.2 通过getEnvironment获取参数
ConfigurableEnvironment environment = annoContext.getEnvironment();
String offline = environment.getProperty("param2.offline");
String domain = environment.getProperty("param2.domain");
System.out.println("domain:" + domain + ",offline:" + offline);
三 通过PropertyPlaceholderConfigurer类读取配置文件
<!-- 方式3:通过PropertyPlaceholderConfigurer类加载 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:param3.properties</value> <!-- web项目可以按下面的方式加载 <value>/WEB-INF/mail.properties</value> --> </list> </property> </bean>
取值方式同方法1。
代码已上传至github,感兴趣的可以一起学习交流~