Spring入门之HelloWorld

本文介绍如何使用MyEclipse创建Spring项目,并演示了通过Java类与Spring配置文件结合实现依赖注入的过程。

1、开发工具 Myeclipse 

2、步骤

(1)新建Java项目

(2)右键点击项目->MyEclipse->Add Spring Capabilities,选择对应的Spring版本号和需要导入的Spring jar包。

(3)新建类HellWorld.java和测试的Test.java,修改配置文件名为beans.xml(文件名称可自定义,个人习惯修改为beans.xml)。

目录清单如下图:

        1.png

(4)HelloWorld.java如下:


package com.spring.bean;

public class HelloWorld {
	private String name;
	
	public void show(){
		System.out.println("Spring,hello,"+name);
	}
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}
(5)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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean id="hellobean" class="com.spring.bean.HelloWorld">
		<property name="name" value="jeff"></property>
	</bean>

</beans>
其中:id为自定义的bean标识名称,唯一,class是和id对应的类全名,property可以该类中的属性进行配置赋值。
(6)测试
package com.spring.test;

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

import com.spring.bean.HelloWorld;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext content = 
                         new ClassPathXmlApplicationContext("beans.xml");
		HelloWorld obj = (HelloWorld) content.getBean("hellobean");
		obj.show();
	}

}
三行代码的意思分别是: 读取配置文件beans.xml
获取bean的idhellobean并返回,转换为HelloWorld类型
调用方法
运行效果如下图:



2.png 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值