Spring
HelloSpring
导入jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
编写代码
编写一个hello实体类
package com.wxt.pojo;
public class Hello {
private String str;
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
编写spring文件,这里我们命名为beans.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">
<!--使用Spring来创建对象,在Spring里这些都称为Bean-->
<!--Bean就是java对象,由Spring创建和管理-->
<bean id="Hello" class="com.wxt.pojo.Hello">
<property name="str" value="helloword"></property>
</bean>
</beans>
测试
public class Mytest {
@Test
public void hh(){
//解析beans.xml文件,生成管理对应的Bean对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//getBean:参数为Spring配置文件中bean的id
Hello hello = (Hello) context.getBean("Hello");
System.out.println(hello.toString());
}
}
思考
- Hello是谁创建的?
hello对象是由spring来创建的
- Hello对象的属性时怎么设置的?
Hello对象的属性是由spring容器设置的
这个过程就叫做控制反转:
- 控制:谁来控制对象的创建,传统应用程序的对象是由程序本身来创建的,使用Spring后,对象是由spring来创建的
- 反转:程序的本身不创建对象,而变成被动的接收对象
依赖注入:就是利用set方法来进行注入的
修改案例一
- 案列一为上章学习笔记里面的 链接为https://blog.csdn.net/qq_44667587/article/details/127909289
我们新增一个Spring配置文件beans.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">
<bean id="Oracle" class="com.wxt.dao.UserDaoJava03Impl">
</bean>
<bean id="MySql" class="com.wxt.dao.UserDaojavaImpl"></bean>
<!--
ref:应用Spring容器中创建好的对象
value:具体的值,基本数据类型
-->
<bean id="ServiceImpl" class="com.wxt.service.UserServiceImpl">
<property name="userDao" ref="MySql" />
</bean>
</beans>
测试类
@Test
public void getUser1(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("ServiceImpl");
serviceImpl.getUser();
}
测试结果
如果我们想通过Oracle来获取用户数据
- 我们并不需要去更改代码,我们只需要去更改配置文件里面的对象
<bean id="ServiceImpl" class="com.wxt.service.UserServiceImpl">
<property name="userDao" ref="Oracle" />
</bean>
测试结果
总结
- OK,到了现在,我们彻底不用再去程序中更改或变动了,要想实现不同的操作,我们只需要在xml配置文件中进行修改,所谓的IOC,一句话搞定;对象由Spring来创建,管理,装配!