【尚硅谷】spring学习笔记(1):HelloWorld

1、安装SPRING TOOL SUITE 这个 Eclipse 插件。

2、搭建spring开发环境,引入jar包。

3、创建spring项目

3.1、创建一个HelloWorld类

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

3.2、创建一个配置文件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.atguigu.spring.helloworld.HelloWorld2">
	    <property name="name" value="ligang"></property>
	</bean>
</beans>

3.3、创建 Spring 的 IOC 容器,并从IOC容器里面获取bean是实例,并使用bean

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
	
	public static void main(String[] args) {

		//1. 创建 Spring 的 IOC 容器(单独这条语句会初始化构造器和类方法)
		ClassPathXmlApplicationContext cpa = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		//2. 从 IOC 容器中获取 bean 的实例
		HelloWorld2 helloWorld = (HelloWorld2) cpa.getBean("helloWorld");
		
		//3. 使用 bean
		helloWorld.hello();

3.4、输出

六月 06, 2018 11:59:23 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6193b845: startup date [Wed Jun 06 11:59:23 CST 2018]; root of context hierarchy
六月 06, 2018 11:59:23 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
您好:ligang

猜你喜欢

转载自blog.csdn.net/oqkdws/article/details/80592912