Spring学习总结(3)-了解Spring框架

Spring的核心Jar包

在Spring4的官方文档里,提到了Sping的核心包是:spring-context,只要引用了这个jar包,就可以实现Spring90%的基础功能。maven引用如下:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

而在Spring5时,就不再这么说了,因为Spring5推荐用户使用Spring Boot构建项目。

测试Spring的几种方法:

1. 在main方法中使用ClassPathXmlApplicationContext,这个类可以加载Spring的配置文件,下面的getBean是使用byName方式自动注入的。 

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
        UserService service = (UserService)contex.getBean("service");
        service.getUser();
    }
}

2. 在main方法中使用AnnotationConfigApplicationContext,这个类可以加载Spring的启动类,或者有@Configuration注解的类,这里的getBean使用的是byType方式注入。@ComponentScan注解是声明Spring要扫描资源的包路径。

import com.zh.service.SpringConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService bean = context.getBean(UserService.class);
        bean.getUser();
    }
}
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.zh.service")
public class SpringConfig {
}

 3. 使用spring-test包,如果你使用的spring boot构建项目,只需要使用spring-boot-starter-test包就可以了,因为它里面带了spring-test

<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.0.RELEASE</version>
    <scope>test</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>2.1.8.RELEASE</version>
    <scope>test</scope>
</dependency>

spring boot的测试方法,如果是Spring Cloud的话,注解需要这么写:@SpringBootTest(classes={ServerApplication.class,UserServiceTest.class}) ,其中ServerApplication是Spring Cloud的启动类,UserServiceTest是当前的测试类。

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {
        @Autowired
        private UserService userService;

        @Test
        public void getUser(){
               userServce.getUser();
        }

}

猜你喜欢

转载自www.cnblogs.com/huanshilang/p/11689301.html