1. 通过xml方式加载配置
以Spring实例化dataSource为例,先在工程目录的src下新建一个conn.properties文件,里面写上上面dataSource的配置:
dataSource=com.mchange.v2.c3p0.ComboPooledDataSource driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/shop username=root password=root
然后在只需要在beans.xml中做如下修改即可:
<context:property-placeholder location="classpath:conn.properties"/><!-- 加载配置文件 --> <!-- com.mchange.v2.c3p0.ComboPooledDataSource类在c3p0-0.9.5.1.jar包的com.mchange.v2.c3p0包中 --> <bean id="dataSource" class="${dataSource}"> <!-- 这些配置Spring在启动时会去conn.properties中找 --> <property name="driverClass" value="${driverClass}" /> <property name="jdbcUrl" value="${jdbcUrl}" /> <property name="user" value="${user}" /> <property name="password" value="${password}" /> </bean>
在java代码中用@Value获取配置属性值
@Value("${shop.url}")
private String url;
2.0 spring注解加载配置
@Configuration
@PropertySource("classpath:jdbc.properties")
//@ConfigurationProperties(prefix = "demo")使用这个可以省略@value
public class JdbcConfig{
@Value("jdbcUrl")
String jdbcUrl;
@Value("driverClass")
String driverClass;
@Value("user")
String user;
@Value("password")
String password
@DataSource
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDrieverClassName(driverClass);
dataSource.setUrl(jdbcUrl);
dataSource.setUserName(user);
dataSource.setPassword(password);
return dataSource;
}
}