设为首页 加入收藏

TOP

学习笔记——Spring中组件扫描(包含扫描、排除扫描)、Spring中完全注解开发;Spring整合Junit4步骤
2023-07-25 21:42:32 】 浏览:33
Tags:习笔记 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());
    }
}

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇学习笔记——Git命令 下一篇Error querying database. Cause:..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目