zl程序教程

您现在的位置是:首页 >  其他

当前栏目

学习笔记——Spring中组件扫描(包含扫描、排除扫描)、Spring中完全注解开发;Spring整合Junit4步骤

2023-03-31 10:39:19 时间

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());
    }
}