spring基础篇-入门篇
本篇承接上篇基础入门篇,又不了解spring是做什么用的小伙伴,可以先看看上一篇文章。
本系列文章全部采用idea作为开发工具,使用maven仓库,有不了解小伙伴可以先自行了解。
Ioc(Inversion of Controller)概念
中文名控制反转,顾名思义,就是将对象的控制权进行翻转,原本对象的创建,初始化,销毁等操作全部在开发者自己手中,而现在将这些控制权交规容器来完成,开发者就可以从对象的创建中解脱出来,更多地专注于业主,好了,废话不多说,直接上代码。
加入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.18.RELEASE</version>
</dependency>
创建一个玩具类
public class Toy {
private int numberNO;
private String name;
private Double price;
//省略getter setter方法
}
在创建一个孩子类,让孩子拿到玩具
public class children {
private int age;
private String name;
public void getToy(){
Toy toy = new Toy();
toy.setName("小火车");
toy.setNumberNO(1);
toy.setPrice((double)20.0);
//省略getter setter方法
}
这样,这个玩具始终都只在一个孩子手上,但如果另一个孩子也想玩,这个时候,就只能大人再去买一个,而如果大人(开发者)没有时间,那么第二个玩具由谁去购买呢,这就是容器的作用,类似于佣人一样,孩子可以直接向佣人去要,而不需要大人(开发者)自己去花费精力
使用spring的之后,我们就可以将bean的创建,初始化,销毁等操作,全部交给spring容器去完成。只需要在项目初始化的时候,将bean注册到spring容器中,等到其他对象再需要的时候,就不用我们手动去new了。
首先,在resource目录下,创建一个spring的配置文件,注意,一定是在加入了spring依赖之后。
将toy(玩具类)交给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">
<bean class="org.zhiqiu.springdemo01.bean.Toy" id="toy"/>
</beans>
Class作为bean的全路径,id则作为bean的唯一标识符,配置好之后,我们来加载这个配置文件。
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Toy toy = (Toy) context.getBean("toy");
System.out.println(toy);
}
ClassPathXmlApplicationContext 会去classpath下查找配置文件,也可以使用 FileSystemXmlApplicationContext会从操作系统路径下开始寻找,即,
new FileSystemXmlApplicationContext("F:\\work\springdemo01\\applicationContext.xml")
除了上述或许bean的方式外,还可以通过bean.class来获取,如下`
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Toy toy = context.getBean(Toy.class);
System.out.println(toy);
}
注意,这样获取虽然不需要强转,但也有一个缺点,就是在xml中只有一个bean的情况下,如果有多个bean,则会报错,所以一般建议,使用id 或者name来获取bean的实例。
属性注入
学习spring ,必不可不学的就是xml配置,在早期的spring项目中,xml配置有很多,如果不了解xml配置,维护一些老项目,都是一件很头疼的事情。
首先,我们来看第一种属性注入方式,构造方法注入
<bean class="org.zhiqiu.springdemo01.bean.Toy" id="toy">
<constructor-arg name="name" value="机器人"/>
<constructor-arg name="numberNO" value="007"/>
<constructor-arg name="price" value="100.00"/>
</bean>
运行之前的Main方法可以看到,会将注入的属性打印出来。
除了name按名称注入之外,还有按index下表注入,不过这种方式并不推荐,因为如果类中属性多了,就会很难记忆数量顺序。
按照set方法注入
<bean class="org.zhiqiu.springdemo01.bean.Toy" id="toy">
<property name="name" value="机器人"/>
<property name="numberNO" value="004"/>
<property name="price" value="144.00"/>
</bean>
这里有一点要注意的是,注入的属性名并不是类中定义的属性名,而是通过反射,java内部机制分析出来的属性名。