Spring-01 入门

1)创建Maven版的Java工程

在这里插入图片描述

加入Spring相关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
commons-logging-1.1.1.jar

<dependencies>
  		<!-- beans  -->
  		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>4.0.0.RELEASE</version>
		</dependency>
		
		<!-- context -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.0.0.RELEASE</version>
		</dependency>
		
		<!-- core -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.0.0.RELEASE</version>
		</dependency>
		
		<!-- expression -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>4.0.0.RELEASE</version>
		</dependency>
		  
</dependencies>

创建Spring配置文件

取名applicationContext.xml
在这里插入图片描述

创建HelloWorld类

public class HelloWorld {

	private String name;
	
	public HelloWorld() {
		System.out.println("HelloWorld对象被创建了");
	}
	
	public void setName(String name) {
		System.out.println("name属性被赋值了");
		this.name = name;
	}
	
	public void sayHello() {
		System.out.println("Hello: "+name);
	}
}

配置Spring配置文件

<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 配置bean
        id属性:配置bean的名称,该属性值在IOC容器中是唯一的
        class属性:配置bean的全类名,Spring会利用反射技术实例化该bean
    -->
    <bean id="helloWorld" class="com.atguigu.spring.helloworld.HelloWorld">
        <!-- 通过property标签给bean的属性赋值 -->
        <property name="name" value="Spring"></property>
    </bean>
</beans>

测试

通过Spring的IOC容器创建HelloWorld类实例

@Test
	void test() {
		//1.创建IOC容器对象
		ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
		//2.从IOC容器中获取HelloWorld对象
		HelloWorld helloWorld = (HelloWorld) ioc.getBean("helloWorld");
		//3.调用HelloWorld中的sayHello方法
		helloWorld.sayHello();
	}

在这里插入图片描述

发布了274 篇原创文章 · 获赞 97 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/imxlw00/article/details/104755913