1在XML中的配置方式
<!-- 添加context命名空间 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 导入外部properties文件到ioc上下文中 -->
<context:property-placeholder location="jdbc.properties" />
<!-- 使用占位符的方式获取properties文件中的属性值 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" initmethod="init" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
</bean>
2在注解中的配置方式
通过 @PropertySource 注解可以将外部properties文件导入到上下文中,通过 @Value 注解可以获取 properties文件中的属性值,并注入到当前类的属性中
@Configuration
@ComponentScan(basePackages = "com.spring")
@PropertySource("classpath:jdbc.properties")
public class MyConfiguration {
}
@Component
public class MyDataSourceAnno {
//@Value : 获取外部配置文件的内容
@Value("${jdbc.dirver}")
private String driverClass;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.name}")
private String name;
@Value("${jdbc.passWord}")
private String passWord;
.......
}