@Value注入普通数据


@Value注解的作用: 注入普通数据类型。

一、编写Bean类

CustomerDao接口:

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

CustomerDaoImpl实现类:

package com.yiidian.dao.impl;

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

import com.yiidian.dao.CustomerDao;
/**
 * @author http://www.yiidian.com
 *
 */
@Component(value="customerDao")
public class CustomerDaoImpl implements CustomerDao {
	//2Value注入普通数据
	@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
				+ "]";
	}
}

二、配置applicationContext.xml

在scr目录建立jdbc.properties

jdbcUrl=jdbc:mysql:///spring
driverClass=com.mysql.jdbc.Driver
user=root
password=root

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	
	<context:property-placeholder location="classpath:jdbc.properties"/>

	<!-- 开启SpringIOC注解扫描 -->
	<context:component-scan base-package="com.yiidian.dao"></context:component-scan>
	
	
</beans>

三、编写测试类

package com.yiidian.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yiidian.dao.CustomerDao;
/**
 * @author http://www.yiidian.com
 *
 */
public class Demo1 {
	
	@Test
	public void test1(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerDao customerDao = (CustomerDao)ac.getBean("customerDao"); 
		System.out.println(customerDao);
	}
}

四、运行结果

 

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