3.1、 XML配置文件实现
实体类:
package com.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
XML配置文件:
_ 使用Spring来创建对象, 在Spring中这些对象都称为Bean
类型 变量名 = new Hello();<br /> bean = 对象 new Hello();
id=变量名<br /> class= new 的对象<br /> property= 给对象中的属性设置了一个值_<br />__
为class中的对象赋值 该属性必须要有Set方法!!
<?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 Hello();
bean = 对象 new Hello();
id=变量名
class= new 的对象
property= 给对象中的属性设置了一个值
-->
<bean id="hello" class="com.pojo.Hello">
<!--为class中的对象赋值 该属性必须要有Set方法-->
<property name="str" value="SpringHello啊!"/>
</bean>
</beans>
测试类:
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象!(用于获取XML配置文件的方法)(固定)
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在Spring中管理了, 我们要使用, 直接去里面取出来就可以了(getBean方法)
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
3.2、Spring-01-ioc01 的改进
1、接口与实现类

2、bean配置
<?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 Hello();
bean = 对象 new Hello();
id=变量名
class= new 的对象
property= 给对象中的属性设置了一个值
-->
<bean id="mysqlImpl" class="com.dao.UserDaoMysqlImpl"/>
<bean id="orcaImpl" class="com.dao.UserDaoOrcaImpl"/>
<!--ref: 引用Spring容器中创建好的对象
value: 具体的值, 基本数据类型!
-->
<bean id="UserServiceImpl" class="com.service.UserServiceImpl">
<property name="userDao" ref="orcaImpl"/>
</bean>
<!--为class中的对象赋值 该属性必须要有Set方法-->
</beans>
3、测试
import com.service.UserServiceImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
// //用户调用的实际上是Service层,不会直接接触Dao层
// UserServiceImpl userService = new UserServiceImpl();
//
// //这里能够让用户获得控制权
// userService.setUserDao(new UserDaoOrcaImpl());
//
// userService.getUser();
//获取ApplicationContext: 拿到Spring的容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//需要什么就get什么
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
}
}
OK, 到了现在我们彻底不用改程序了, 要实现不同的操作, 只需要在XML配置文件中修改就行了, 所谓的IOC, 一句话搞定: 对象由Spring来创建、管理、装配
本文介绍了如何通过 XML 配置文件实现 Spring 的依赖注入(IOC),包括实体类定义、配置文件设置及测试验证过程。进一步展示了通过 Spring 容器管理不同实现类,实现灵活的接口实现选择。
643

被折叠的 条评论
为什么被折叠?



