3.1、Spring-01
1.编写实体类:
@Data
public class Hello {
private String str;
}
2.编写Sping配置文件
官网:
<?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 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>
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 类型();
java新建对象:Hello hello = new Hello();
bean新建对象
id = 变量名
class = new的对象(全路径)
property:给对象设置一个值
-->
<bean id="hello" class="com.mosang.dao.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
3.测试
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//对象都在bean中管理,直接从bean中取出即可
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
总结:
-
Hello对象是由Spring创建的,Hello对象的属性是由SPringle容器设置的
-
控制反转:
-
控制:控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring创建的
-
反转:程序本身不创建对象,而变成被动的接收对象
-
-
依赖注入:利用Set方法注入
3.2、service层调dao层
1.xml文件的配置
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
<?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="UserDaoImpl" class="com.mosang.dao.UserDaoImpl"/>
<bean id="UserServiceImpl" class="com.mosang.service.UserServiceImpl">
<property name="userDao" ref="UserDaoImpl"/>
<!-- 必须需要set方法-->
<!--name:set方法的参数名
ref:引用 另一个bean-->
</bean>
</beans>
2.测试
public class MyTest {
public static void main(String[] args) {
//获取ApplicationContext;拿到Spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
}
}
现在 , 不用再程序中去改动了 , 要实现不同的操作 , 只需要在xml配置文件中进行修改 .
所谓的IoC: 对象由Spring 来创建 , 管理 , 装配 !