2021-05-03 09:46  阅读(134)
文章分类:Spring 入门教程 文章标签:SpringSpring 教程
©  原文作者:一点教程 原文地址:http://www.yiidian.com/spring/

@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);
    	}
    }
    

三、运行结果

c27f6a691a4c9e59a06b68549753d98d.png

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

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

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> 零配置-@PropertySource
上一篇
零配置-@ComponentScan
下一篇
零配置-@Import