现在的步骤:
- 使用 meven 导入相关的包
org.springframework spring-webmvc 5.3.21 org.springframework spring-jdbc 5.3.21
- 写一个 Hello 实体类
package top.muquanyu.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + ''' +
'}';
}
public void setStr(String str) {
this.str = str;
}
}
- 写一个 beans.xml 配置文件
- 实操部分
- 根据 xml 文件,获取 上下文对象
// 获取 spring 的上下文 对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
- 从容器中 拿到 我们刚才 设定的 Bean,任意 对象 都可以 在 xml 中 设定为 Bean。
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import top.muquanyu.pojo.Hello;
public class Test {
public static void main(String[] args) {
// 获取 spring 的上下文 对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 从容器中 去拿出 设定的对象,这些对象 都是 Bean
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
这其实 就实现了 控制反转,我们通过 xml 文件配置 相关信息的方式,也就是 第三方。创建了一个 Hello 对象,并且 用 xml 文件配置 设定了 该对象的 str 属性值 为 “Spring”。
ClassPathXmlApplicationContext 其实实现了很多接口,哈哈。十分的不容易。
3.2 使用 Spring 的 IOC思想
ref:赋值 xml 文件 当中 配置好的 一些 bean 对象。
value:具体的一个常数值。
package top.muquanyu.service;
import top.muquanyu.dao.UserDao;
import top.muquanyu.dao.UserDaoImpl;
import top.muquanyu.dao.UserMySQLImpl;
public class UserServiceImpl implements UserService{
private UserDao userDao = new UserDaoImpl();
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void printUser() {
System.out.println(userDao.getUser());
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import top.muquanyu.dao.UserDaoImpl;
import top.muquanyu.dao.UserMySQLImpl;
import top.muquanyu.service.UserService;
import top.muquanyu.service.UserServiceImpl;
public class MyTest {
public static void main(String[] args) {
// UserServiceImpl userService = new UserServiceImpl(new UserDaoImpl());
// userService.printUser();
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl)context.getBean("UserServiceImpl");
userServiceImpl.printUser();
}
}



