2023-01-18 一、Spring中組件掃描 1、預設使用的情況 <context:component-scan base-package="com.hh"></context:component-scan> 2、包含掃描 註:使用包含掃描之前,必須設置use-default-filters=" ...
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()); } }