Spring学习(一)| HelloWorld

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();
	}
}

猜你喜欢

转载自blog.csdn.net/ljcaidn/article/details/83352979