Hello Spring
导入jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
编写代码
- 编写一个实体类
/*
实体类Hello
*/
public class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Hello{" +
"name='" + name + '\'' +
'}';
}
}
2.编写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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用spring来创建我们的对象,在spring这些都称为bean
类型 变量名 = new 类型();
id=变量名
class= new 的对象(全路径)
property 相当于给对象中的属性设置一个值
bean = 对象 相当于 new Hello();
-->
<bean id="hello" class="com.yoda.pojo.Hello">
<property name="name" value="Spring"/>
</bean>
</beans>
3.进行测试
/*
测试
*/
public class MyTest {
public static void main(String[] args) {
//获取spring的上下文对象!
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在spring中管理,我们要使用,直接去里面取出来即可
//利用id定位到IOC容器中的bean
Hello hello = (Hello)context.getBean("hello");
System.out.println(hello.toString());
}
}
总结:
- Hello对象是由spring创建
- Hello对象的属性是由Spring容器(beans)设置的
- 这个过程就是控制反转(IOC):
控制(控制对象的创建):原先应用程序的对象是由程序本身控制创建(new 对象),使用spring后,对象是由spring来创建
反转:程序本身不创建对象,而变成被动的接收对象
4.依赖注入:利用set方法进行依赖注入
实质:IOC就是一种编程思想,就是将主动编程变成被动接收的过程!!
在之前的案例中添加一个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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
使用spring来创建我们的对象,在spring这些都称为bean
类型 变量名 = new 类型();
id=变量名
class= new 的对象(全路径)
property 相当于给对象中的属性设置一个值
bean = 对象 相当于 new Hello();
-->
<bean id="MysqlImpl" class="com.yoda.dao.UserDaoMysqlImpl"/>
<bean id="OracleImpl" class="com.yoda.dao.UserDaoOracleImpl"/>
<!--
ref: 引用Spring容器中创建好的对象
value : 具体的值,基本数据类型!
-->
<bean id="UserServiceImpl" class="com.yoda.service.UserServiceImpl">
<property name="userDao" ref="MysqlImpl"/>
</bean>
</beans>
测试
/*
测试
*/
public class MyTest2 {
public static void main(String[] args) {
//获取ApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//容器在手,天下我有! 需要什么 ,直接get 即可
UserServiceImpl userServiceImpl =(UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
}
}
- 类似于工厂模式
- 现在 我们彻底不用再程序中去改动了 , 要实现不同的操作 , 只需要在xml配置文件中进行修改 , 所谓的IoC,一句话搞定 : 对象由Spring 来创建 , 管理 , 装配 !