Spring第一课:配置文件及IOC引入(一)

Spring最核心的特点就是控制反转:(IOC)和面向切面(AOP)

首先作为一个Spring的项目需要导入的四个核心包,一个依赖:

四核心:core、context、beans、expression

一个依赖:commons-loggins.jar

其次注意在Spring的jar包中,有三种文件:

1.字节码文件[真正使用的jar包]

2.文档-javadoc

3.源码文件-sources

关于Spring的配置文件:

位置:我们一般放在src(classpath)下。

名字:名字一般取名applicationContext.xml。

内容:添加schema约束。[约束文件位置:docs\spring-framework-reference\html\ xsd-config.html]

以上都是一般的开发规则:是约定俗称,但并不是必须;

位置任意、名字任意,但是内容必须是schema约束!

测试控制反转:

service的接口

package com.a_ioc;

public interface UserService {
	boolean addUser();
}

service的impl:

package com.a_ioc;

public class UserServiceImpl implements UserService{

	@Override
	public boolean addUser() {
		System.out.println("add user");
		return false;
	}

}

位于和当前类同包块下的beans.xml[其实就是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/beans 
       					   http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- 配置所需要创建对象,id用于之后从Spring中获得实例时使用的,class需要创建实例的全限定类名 -->
	<bean id="UserService" class="com.ioc.UserServiceImpl"></bean>
</beans>

因为当前的Spring的配置文件是位于当前的包块下面,而默认的寻径位置又是在src下面,所以必须从src下面开始找,并且xml名称为beans.xml

package com.a_ioc;

import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestIoc {
	
	// IOC:控制反转
	@Test
	public void testCreateBean() {
		// 从Spring容器中获得:因为默认是从src下走的,所以使用src下相对路径来找
		String xmlPath = "com/ioc/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		
		// 不需要自己new,都是从Spring容器中获得
		UserService userService = (UserService) applicationContext.getBean("UserService");
		userService.addUser();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_36791569/article/details/81181247