零配置-@PropertySource

@PropertySource注解,用于代替<context:property-placeholader/>配置,加载properties配置文件。

一、编写Bean类

CustomerDao接口:

package com.yiidian.dao;
/**
 * 
 * @author http://www.yiidian.com
 *
 */
public interface CustomerDao {
	public void save();
}

CustomerDaoImpl实现:

package com.yiidian.dao.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.yiidian.dao.CustomerDao;

/**
 * @author http://www.yiidian.com
 * 
 */
@Repository(value = "customerDao")
public class CustomerDaoImpl implements CustomerDao {

	@Value("${jdbcUrl}")
	private String jdbcUrl;
	@Value("${driverClass}")
	private String driverClass;
	@Value("${user}")
	private String user;
	@Value("${password}")
	private String password;

	@Override
	public String toString() {
		return "CustomerDaoImpl [jdbcUrl=" + jdbcUrl + ", driverClass="
				+ driverClass + ", user=" + user + ", password=" + password
				+ "]";
	}

	@Override
	public void save() {
		System.out.println("执行了CustomerDaoImpl的save()方法");
	}

}

SpringConfig启动类(重点在这里):

package com.yiidian.test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @author http://www.yiidian.com
 *
 */
@Configuration
@ComponentScan(basePackages={"com.yiidian"}) 
@PropertySource(value="classpath:jdbc.properties") //加载jdbc.properties文件,以便@Value注解获取文件值
public class SpringConfig {
}

二、编写测试类

package com.yiidian.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.yiidian.dao.CustomerDao;

public class Demo1 {
	@Test
	public void test1(){
		ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
		CustomerDao customerDao = (CustomerDao)ac.getBean("customerDao");
		System.out.println(customerDao);
	}
}

三、运行结果

成功读取了jdbc.properties文件的内容!

 

源码下载:http://pan.baidu.com/s/1qXVQPzu

热门文章

优秀文章