Spring学习(一)| HelloWorld

本文通过创建一个简单的Java项目,详细介绍了如何使用Spring框架进行依赖注入和配置JavaBean。步骤包括项目搭建、类定义、XML配置及运行主函数。

1. 新建项目

  • 新建一个java project
  • 新建一个lib文件夹,导入以下五个包,并且build path

    commons-logging-1.2.jar
    spring-beans-4.3.9.RELEASE.jar
    spring-context-4.3.9.RELEASE.jar
    spring-core-4.3.9.RELEASE.jar
    spring-expression-4.3.9.RELEASE.jar

2. 一个简单的 HelloWorld.java 类

public class HelloWorld {
	private String name;

	public void setName(String name) {
		System.out.println("setName" + name);
		this.name = name;
	}
	
	public void hello() {
		System.out.println("hello: " + name);
	}

	public HelloWorld() {
		System.out.println("HelloWorld's Construtor...");
	}
}

3. 配置JavaBean

  • /src目录下新建 javabean配置 xml 文件
  • 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  -->
	<bean id="helloWorld" class="com.spring.demo.HelloWorld">
		<property name="name" value="Spring"></property>
	</bean>
	
	
</beans>

4. 写主函数

public class Main {
	public static void main(String[] args) {
		
		//1. 创建Spring的 IOC 容器对象
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

		//2.从IOC 容器中获取Bean实例
		HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
		
		//3.调用函数
		helloWorld.hello();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值