使用@PropertySource加载外部配置文件属性赋值
1、新建一个spring组件配置类:
package com.gwolf.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.gwolf.vo.Connection;
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Connection connection() {
return new Connection();
}
}

2、新建一个properties配置文件:
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root

3、在组件配置类中使用@PropertySource注解导入*.properties配置文件:
package com.gwolf.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import com.gwolf.vo.Connection;
@Configuration
@PropertySource("classpath:dbconfig.properties")
public class MainConfigOfPropertyValues {
@Bean
public Connection connection() {
return new Connection();
}
}

4、在VO对象中通过${}注入properties文件中的值到VO中。
package com.gwolf.vo;
import org.springframework.beans.factory.annotation.Value;
public class Connection {
@Value("${jdbc.jdbcUrl}")
private String jdbcUrl;
@Value("${jdbc.driverClass}")
private String driverClass;
@Value("${jdbc.user}")
private String user;
@Value("${jdbc.password}")
private String password;
public String getJdbcUrl() {
return jdbcUrl;
}
public void setJdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Connection [jdbcUrl=" + jdbcUrl + ", driverClass=" + driverClass + ", user=" + user + ", password="
+ password + "]";
}
}

5、编写一个junit测试类,得到容器中的bean对象的值,打印bean的值。
package com.gwolf.test;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.gwolf.config.MainConfigOfPropertyValues;
public class ComponentTest {
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
@Test
public void testImport() {
String[] beanNames = applicationContext.getBeanDefinitionNames();
System.out.println(applicationContext.getBean("connection"));
applicationContext.close();
}
}
