spring扫描指定包下的class(学习笔记——Spring中组件扫描(包含扫描、排除扫描)、Spring中完全注解开发;Spring整合Junit4步骤)
导读:2023-01-18...
2023-01-18
一 、Spring中组件扫描
1 、默认使用的情况
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());
}
}
声明:本站所有文章 ,如无特殊说明或标注 ,均为本站原创发布 。任何个人或组织 ,在未征得本站同意时 ,禁止复制 、盗用 、采集 、发布本站内容到任何网站 、书籍等各类媒体平台 。如若本站内容侵犯了原著者的合法权益 ,可联系我们进行处理。
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!