Spring系列二:基本使用

1、把以下 jar 包加入到工程的 classpath 下:
 commons-logging-1.1.1.jar
 spring-beans-4.0.0.RELEASE.jar
 spring-context-4.0.0.RELEASE.jar
 spring-core-4.0.0.RELEASE.jar
 spring-expression-4.0.0.RELEASE.jar
2、Spring 的配置文件:一个典型的 Spring 项目需要创建一个或多个 Bean 配置文件,这些配置文件用于在 Spring IOC 容器里配置 Bean。Bean 的配置文件可以放在 classpath 下,也可以放在其它目录下。
3、测试:
创建bean

public class HelloWorld {

	private String name;

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

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

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

向Spring中注册bean

<!-- 配置一个 bean -->
<bean id="helloWorld" class="com.atguigu.spring.helloworld.HelloWorld">
	<!-- 为属性赋值,对应属性的set方法-->
	<property name="name2" value="Spring"></property>
</bean>

在创建 IOC 容器容器时,会调用 HelloWorld 的构造器创建对象,并调用set方法为属性赋值

public class Main {
	
	public static void main(String[] args) {
		
		//1. 创建 IOC 容器
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		//2. 从 IOC 容器中获取 bean 实例
		HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
		
		//3. 调用 bean 的方法
		helloWorld.hello();
	}
	
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值