java spring(1) HelloWorld

本文介绍如何使用Eclipse安装Spring插件,并通过示例代码演示Spring框架的基本使用方法,包括创建Spring IOC容器、定义Bean及依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一. spring 的eclipse 插件

     eclipse -->Help--> install new-->add --> location = http://springide.org/updatesite

     勾选4个带IDE 的项目,如图1


图 1 


二. 代码(具体的spring 创建步骤,以及每一步的作用,在代码的注释文件中有)

1. 代码 bean 类HelloWorld.java

package com.atguigu.spring.beans;

/**
 * Hello world!
 *
 */
public class HelloWorld 
{
	private String name;
	
	public void setName2(String name){
		System.out.println("setName方法:"+name);
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void hello(){
		System.out.println("hello: "+name);
	}
	public HelloWorld(){
		System.out.println("helloworld constructor");
	}
}

代码service 类  Main.java

package com.atguigu.spring.beans;

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

public class Main {

	public static void main(String[] args) {
		/*  传统方法,需要3步。而用了spring 之后,第一步第二步可以交给spring 来做 
		//1.创建HelloWorld  的一个对象
		HelloWorld helloWorld = new HelloWorld();
		//2.为name 属性赋值
		helloWorld.setName("atguigu");
		*/
		//3.调用hello 方法
		//helloWorld.hello();
		
		///////////////////////////////spring 方法创建对象////////////////////////////////
		
		//1.创建Spring 的IOC 容器对象     如果只执行这一句,spring帮我们做两件事,构造方法 helloworld constructor  set 方法 setName方法:Spring
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");//ApplicationContext 是个接口,代表spring里面的IOC 容器
		
		//2.从IOC 容器中获取Bean 实例
		//HelloWorld helloWorld = (HelloWorld)ctx.getBean("helloWorld");//参数是bean 的id
		//3. 调用hello 方法
		//helloWorld.hello();
	}

}

配置文件applicationContext.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 --><!-- 这里的name 属性要和类中的set方法后面的名字相对应 -->
		<bean id="helloWorld" class="com.atguigu.spring.beans.HelloWorld"><!-- class 是全类名,id 是类名第一个字母小写 -->
			<property name="name2" value="Spring"></property><!-- 这是是用反射的方式,由spring 帮我们创建一个对象 -->
		</bean>	
</beans>

4. 代码结构如图2


    图 2


5. 运行结果

hello: spring






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值