学习笔记——Spring中组件扫描(包含扫描、排除扫描)、Spring中完全注解开发;Spring整合Junit4步骤
2023-01-18
一、Spring中组件扫描
1、默认使用的情况
<context:component-scan base-package="com.hh"></context:component-scan>
2、包含扫描
注:使用包含扫描之前,必须设置use-default-filters="false"(关闭当前包及其子包的扫描)
type类型:
①annotation:设置被扫描注解的全类名
②assignable:设置被扫描实现类的全类名
<context:component-scan base-package="com.hh" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> <!-- <context:include-filter type="assignable" expression="com.hh.service.DeptService"/>--> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
3、排除扫描
<context:component-scan base-package="com.hh" use-default-filters="false"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
二、Spring中完全注解开发
1、完全注解开发步骤
(1)创建配置类
@Configuration @ComponentScan(basePackages = "com.hh") public class SpringConfig { }
(2)在class上面添加注解
①@Configuration:标识当前类是一个配置类,作用:代替XML配置文件
②@ComponentScan:设置组件扫描的当前包及其自包
(3)使用AnnotationConfigApplicationContext容器对象
public class Test0Xml { @Test public void test0Xml(){ //创建一个容器对象 // ApplicationContext context = new ClassPathXmlApplicationContext(""); ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); DeptDaoImpl deptDao = context.getBean("DeptDao", DeptDaoImpl.class); System.out.println("deptDao = " + deptDao); } }
三、Spring整合Junit4步骤
1、集成步骤
(1)导入jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.10</version> <scope>test</scope> </dependency>
(2)指定Spring的配置文件的路径(@ContextConfiguration)
(3)指定Spring环境下运行Junit4的运行器
①RunWith
(4)集成示例
@ContextConfiguration(locations = "classpath:applicationContext.xml") @RunWith(SpringJUnit4ClassRunner.class) public class TestSpringJunit4 { @Autowired private DeptService deptService; @Test public void testService(){ //创建容器对象 // ApplicationContext context = // new ClassPathXmlApplicationContext("applicationContext.xml"); // DeptService deptService = context.getBean("deptService", DeptServiceImpl.class); deptService.saveDept(new Dept()); } }
分类:
SSM
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南