Spring入门之第一课

61 阅读2分钟

1.spring是什么

学过Java的都知道,spring是一门强大的框架,被誉为程序员的春天,那么他到底强大在哪里呢?

spring包括许多框架,例如 Spring framework、SpringMVC、SpringBoot、Spring Cloud、Spring Data、Spring Security 等,故很多人称之为:Spring 全家桶。

Spring framework也就是spring框架,是全家桶内其它框架的基础和核心。

Spring 是分层的 Java SE/EE 一站式轻量级开源框架,有两个中心:分别是 IoC(Inverse of Control,控制反转)AOP(Aspect Oriented Programming,面向切面编程)

在使用 Spring 之前,对象的创建都是由 new 创建的,例如,UserDao userDao=new UserDaoImpl(), 而使用了Spring,对象的创建便交给了 Spring 框架。

AOP 是一种编程思想,是面向对象编程(OOP)的一种补充,是用来封装多个类的行为,以此减少系统的重复代码,降低模块间的耦合度。另外,AOP 还解决一些系统层面上的问题,比如日志、事务、权限等。

2.Ioc

控制反转,是对对象控制权的转移,从程序代码本身反转到外部的容器中,通过外部容器实现对象的创建,属性的赋值,依赖的管理

IOC的具体实现方式

IOC的具体实现方式为依赖注入:(DI),有两种方式:基于注解的DI与基于xml的DI

IoC容器及IoC容器如何获取对象间的依赖关系

Spring中提供了两种IoC容器:

  • BeanFactory
  • ApplicationContext

具体流程

  • 1)创建项目,导入jar包
  • 2)定义类
  • 3)创建Sqing配置文件,编写bean
  • 4)在测试类中测试

代码实现

<!-- bean标签的作用就是声明某个类的一个对象 -->
<!-- id:对象的名称(自定义) class:类的全限定名 -->
<!-- SomeService s = new SomeServiceImpl(); -->
<!-- spring框架会把好的对象放到mep集合里 -->
<!-- springMap.put("id的值",new SomeServiceImpl()); -->

<bean id="a" class="java.util.Date"></bean>

<!-- property:赋值 -->
<bean id="stu" class="com.xxx.pojo.Student">
	<property name="name" value="张三"></property>
	<property name="age" value="3"></property>
	
</bean>

<!-- set注入:设置值注入,spring调用类的set方法,完成属性赋值 -->
<bean id="st" class="com.xxx.pojo.Student"></bean>

<bean id="stus" class="com.xxx.pojo.Student">
	<property name="name" value="张三三"></property>
	<property name="age" value="3"></property>
	<!-- 引用类型 -->
	<property name="sc" ref="sch"></property>
</bean>
<bean id="sch" class="com.xxx.pojo.School">
	<property name="name" value="幼稚园"></property>
	<property name="address" value="南京"></property>
</bean>

以上代码是Sqing配置文件,其文件名一般都为 applicationContext.xml

接下来测试

@Test
public void test() {
	//1.创建spring容器的对象
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	//2.使用getBean方法,getBean(配置文件中bean的id值)
	SomeServiceImpl ss = (SomeServiceImpl) ac.getBean("s");
	ss.some();
	
}
    @Test
public void test1(){
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	Date aa = (Date) ac.getBean("a");
	System.out.println(aa);
}
@Test
public void test2(){
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	Student s = (Student) ac.getBean("stu");
	System.out.println(s);
}
@Test
public void test3(){
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	Student s = (Student) ac.getBean("st");
	System.out.println(s);
}
@Test
public void test4(){
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	Student s = (Student) ac.getBean("stus");
	System.out.println(s);
}
    

由此可以发现,在使用框架之后,学习和调用对象的过程变得更加简单和方便。

以下是部分运行代码截图

image.png

image.png