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就好了,可能是与系统的某个名字重了。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值