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

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

四、运行结果

202105030946024016_1.png

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

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> @Value注入普通数据
上一篇
SpringIOC注解的HelloWorld
下一篇
@Autowired装配实例