白话Spring(基础篇)---参数注入

[一知半解,就是给自己挖坑]

本文,我们将在前面介绍的依赖注入的各种方法之上,详细介绍bean下的参数注入的各种方式。在实际应用中,请读者选择自身需求的方式即可。

a.操作系统:win7 x64

b.开发工具:eclipse mars j2ee版本,maven3.3.2,Spring 4,junit4.12

c.复制Spring03工程,重命名为Spring04工程。具体工程结构图如下:


------------------------------------------------------------------------------------------------------------------------------------------------------

一.基本参数类型注入

1.创建Test.java文件,注意:这里需要引入junit包。具体内容如下:

package com.java.ingo.test;

import org.junit.After;
import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java.ingo.entity.Customer;

/**
 * @author 作者 E-mail:ingo
 * @version 创建时间:2016年2月28日上午19:22:47 类说明
 */
public class Test {
	private ApplicationContext ac = null;
	
	@Before
	public void setUp() throws Exception {
		System.out.println("......junit单元测试是方法之前执行......");
		// 首先读取配置文件,配置文件中的bean将会保存到ApplicationContext的实例中
		ac = new ClassPathXmlApplicationContext("classpath:beans.xml");
	}
	@After
	public void tearDown() throws Exception {
		System.out.println("......junit单元测试是方法之后执行......");
	}

	@org.junit.Test
	public void test1() {
		Customer customer = (Customer)ac.getBean("Customer1");
		System.out.println(customer);
	}
}
2.修改beans.xml文件,具体内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	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">

	<bean id="Customer1" class="com.java.ingo.entity.Customer">
		<property name="name" value="Tom"></property>
		<property name="sex" value="male"></property>
		<property name="age" value="22"></property>
	</bean>
</beans>
3.Customer.java文件有前文Spring03工程中复制而来。这里不再赘述。

4.测试方法:在test1方法上,右键run as--->junit test。观察控制台输出结果即可。

-------------------------------------------------------------------------------------------------------------------------------------------------------

二.使用注入bean的方式注入

1.在beans.xml文件中,加入下面配置:

<bean id="Record2" class="com.java.ingo.entity.Record">
		<property name="company" value="ABCD"></property>
		<property name="position" value="Engineer"></property>
		<property name="address" value="Beijing"></property>
	</bean>
	<bean id="Customer2" class="com.java.ingo.entity.Custom
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值