01-spring_helloworld

demo结构

代码:

HelloWorld.java

package com.demo.beans;

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 Constructor");
	}
}

Main.java

package com.demo.beans;

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

public class Main {

	public static void main(String[] args) {
		/*
		//创建helloworld的一个对象
		HelloWorld helloWorld = new HelloWorld();
		//为name属性赋值
		helloWorld.setName("atguigu");
		*/
		//以上两步可以交给spring来完成
		
		//1.创建spring的IOC容器对象
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		//2.从IOC容器中获取bean实例
		HelloWorld helloWorld = (HelloWorld) context.getBean("helloworld");
		//3.调用hello方法
		//调用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 -->
	<bean id="helloworld" class="com.demo.beans.HelloWorld">
		<property name="name" value="Spring"></property>
	</bean>

</beans>

说明:

1、使用spring的三部:创建springIOC容器对象,从容器中获取bean实例,调用相应的方法

2、去掉1中的第3步,会发现,创建SpringIOC容器的时候,会帮我们初始化好bean实例并且将属性赋好值。

原文地址:https://www.cnblogs.com/boucher/p/5737973.html