spring注解4----@PropertySource

某些值我们需要写在配置文件中,比如driver、url、username、password的值,那如何将这些值读取到呢?这时候我们用@PropertySource这个注解。

首先配置文件我们这么写了:

driver=com.jdbc.mysql.driver
url=localhost://3306/testDB
myname=hahaha
password=123456

然后我们在SpringConfig中加个注解@PropertySource,并加上一个静态方法将配置解析器加载到spring容器中(注意,这里的这个静态方法在高版本中不需要,高版本自带解析器。我现在用的是4.2.4):

@Configuration
@ComponentScan(basePackages="com.dimples")
@Import({JdbcConfig.class})
@PropertySource(value = { "classpath:/com/dimples/config/jdbc_config.properties" })
public class SpringConfig {
	//写个静态方法返回一个配置解析器,并将其加载到spring容器中,注意要是静态的,@Bean也不要忘记写
	@Bean
	public static PropertySourcesPlaceholderConfigurer getPlaceholder(){
		return new PropertySourcesPlaceholderConfigurer();
	}
}

然后在我们的JdbcConfig类中我们就可以这么写了:

public class JdbcConfig {
	@Value("${driver}")
	private String driver;
	@Value("${url}")
	private String url;
	@Value("${myname}")
	private String username;
	@Value("${password}")
	private String password;
	
	@Bean(name="dog")
	public Dog getDog(){
		System.out.println(driver);
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
		return new Dog();
	}
}

测试:

ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);

运行结果:

log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
com.jdbc.mysql.driver
localhost://3306/testDB
hahaha
123456

小细节:我之前名字取的叫username,但得到的结果一直是Administor,后来改成了现在的myname就好了,可能是与系统的某个名字重了。。。

猜你喜欢

转载自blog.csdn.net/dimples_qian/article/details/81479365
今日推荐