第一个Spring程序
通过官方文档,编写第一个Spring程序
-
导入Spring的jar包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.3</version> </dependency>
-
编写实体类
public class Hello { private String name; public void show() { System.out.println("Hello:" + this.name); } @Override public String toString() { return "Hello{" + "name='" + name + '\'' + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
-
编写Spring的核心配置文件,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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--bean就是java对象 , 由Spring创建和管理--> <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here --> </beans>
-
实例化容器,获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
-
测试
@Test public void helloTest(){ // 实例化容器,获取Spring的上下文对象 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 我们的对象现在都由Spring进行管理,如果要使用,直接在容器中取出来就行了 Hello hello = (Hello) context.getBean("hello"); hello.show(); // Hello:Spring }
思考:
- Hello 对象是谁创建的?【Hello对象是由Spring创建的】
- Hello 对象的属性是怎么设置的?【Hello对象的属性是由Spring容器设置的】
这个过程就叫控制反转:
- 控制:谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用Spring后 , 对象是由Spring来创建的。
- 反转:程序本身不创建对象 , 而变成被动的接收对象。
依赖注入:就是利用set
方法来进行注入的。
IOC是一种编程思想,由主动的编程变成被动的接收
可以通过new ClassPathXmlApplicationContext去浏览一下底层源码。
修改之前的项目:
-
新建一个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"> <!-- 将UserDao的实现类托管给Spring --> <bean id="userDao" class="com.jh.dao.impl.UserDaoImpl"/> <bean id="userDaoMysql" class="com.jh.dao.impl.UserDaoMysqlImpl"/> <bean id="userDaoOracle" class="com.jh.dao.impl.UserDaoOracleImpl"/> <!-- 将UserDao的实现注入到UserService的实现类 --> <bean id="userService" class="com.jh.service.impl.UserServiceImpl"> <!-- name并不是属性,而是set方法后面的那部分,首字母小写 --> <!-- 引用另外一个bean,使用ref --> <!-- 基本数据类型,具体的值,使用value --> <property name="userDao" ref="userDao"/> </bean> </beans>
-
获取容器,测试结果
@Test public void springGetUser(){ // 获取容器 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 使用getBean方法取出里面的对象 UserService userService = (UserService) context.getBean("userService"); userService.getUser(); }
OK , 到了现在 , 我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IoC,一句话搞定 : 对象由Spring 来创建,管理,装配 !
懂不懂,都是收获