Spring之HelloWorld

搭建 Spring 开发环境

把以下 jar 包加入到下:
工程的 classpath 

Spring 的配置文件: 一个典型的 Spring 项目需要创建一个或多个 Bean 配置文件, 这些配置文件用于在 Spring IOC 容器里配置 Bean. Bean 的配置文件可以放在 classpath 下, 也可以放在其它目录下.

<?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.xsd">
	
	<!-- 
		id:bean的唯一标识
		class:指定全类名    反射的方式创建对象: 
						Class cls = Class.forName("com.learn.spring.beans.HelloWorld")
						Object obj = cls.newInstance(); // 需要提供默认的构造器.
		property: 通过set方法给指定的属性赋值
	 -->
	<bean id="helloWorld" class="com.learn.spring.beans.HelloWorld">
		<property name="name1" value="Jerry"></property>
	</bean> 
	
</beans>
package com.learn.spring.beans;

public class HelloWorld {
	private String name ;
	
	public HelloWorld() {
		System.out.println("invoke HelloWorld  Constructor.....");
	}

	public String getName() {
		return name;
	}

	public void setName1(String name) {
		System.out.println("invoke HelleWorld setName......");
		this.name = name;
	} 
	
	
	public void sayHello(){
		System.out.println("my name 's " + name );
	}
	
}
package com.learn.spring.test;

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

public class Main {
	public static void main(String[] args) {
		/*//1.new 对象
		HelloWorld  helloWorld = new HelloWorld();
		//2.给name属性赋值
		helloWorld.setName("Tom");
		*/
		
		//1.获取IOC容器
		ApplicationContext ctx = 
				new ClassPathXmlApplicationContext("applicationContext.xml");
		//2.从IOC容器中获取对象.
		//HelloWorld helloWorld = (HelloWorld)ctx.getBean("helloWorld");	
		
		//3.调用方法
		helloWorld.sayHello();		
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值