搭建配置Spring
导入spring基础包:spring-core、spring-beans、spring-context、spring-expression
核心配置文件

配置文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/mvc/spring-util-4.3.xsd">
<bean id="userService" class="com.service.Impl.UserServiceImpl"/>
</beans>
复制到我们的配置文件后左上角会提示“Application context not configured for this file”,点击“Configure application context”,点击OK
编写代码测试
UserServiceImpl.java
package com.service.Impl;
import com.service.UserService;
public class UserServiceImpl implements UserService {
@Override
public void test() {
System.out.println("测试");
}
}
UserService.java(接口)
package com.service;
public interface UserService {
void test();
}
Demo .java
import com.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo {
@Test
public void demo(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) applicationContext.getBean("userService");
// System.out.println(userService);
userService.test();
}
}
测试结果

执行过程分析
BeanFactory:BeanFactory是基础类型的IOC容器,是管理bean容器的根接口,并提供了完整的IOC服务支持。简单来说BeanFactory就是一个管理Bean的工厂,它主要负责初始化各种Bean、调用生命周期等方法
ApplicationContext:ApplicationContext被称为应用上下文,是BeanFactory接口的子接口,在其基础上提供了其他的附加功能,扩展了BeanFactory接口
ClassPathXmlApplicationContext:ClassPathXmlApplicationContext是ApplicationContext的实现类,也在其基础上加了许多附加功能。该类从类路径ClassPath中寻找指定的XML配置文件,找到并完成对象实例化工作
构造器的作用::
1、调用setConfigLocations方法加载项目中的Spring配置文件
2、调用refresh方法刷新容器(bean的实例化就在这个方法中)
声明:以上均是结合上课所讲内容总结
原创链接:https://www.gengruiblog.cn/
本文介绍了如何在Spring框架中配置基础包,解析XML配置文件,重点讲解了ApplicationContext和ClassPathXmlApplicationContext的作用。通过实例演示了如何使用这些工具来创建和测试UserService接口和实现类。
407

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



