使用Spring Boot进行单元测试时,发现使用@Autowired注解的类无法自动注入,当使用这个类的实例的时候,报出NullPointerException,即空指针异常. Spring Boot中的单元测试 先简单说一下Spring Boot中的单元测试. 要在Spring Boot中使用单元测试是很简单的,Spring Boot提供了spring-boot-starter-test的依赖,即JUnit的相关依赖. 在pom.xml文件中引入依赖: <dependency> <g…
Application 启动类: @SpringBootApplication @EnableConfigurationProperties @ComponentScan(basePackages = { "com.testing"}) public class Application { @Bean RestTemplate restTemplate() { return new RestTemplate();} public static void main(String[] ar…
无法注入原因: 有的时候我们有一些类并不想注入Spring容器中,有Spring容器实例化,但是我们又想使用Spring容器中的一些对象,所以就只能借助工具类来获取了 工具类: package com.mikey.design.utils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import o…
import org.junit.Test;import org.junit.runner.RunWith;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springfr…
今天编写了个工具类需要用到service成和dao层的代码 如下: //第一步:需要将工具类注入到容器中 @Component public class RuleUtils { ​ //第二部注入 @Autowired private BsVehicleInfoServiceImpl bsVehicleInfoImpl; @Autowired private BsAlarmInfoMapper alarmInfoMapper; //第三步 建一个静态的本类 private static Rule…
spring注解的作用: 1.spring作用在类上的注解有@Component.@Responsity.@Service以及@Controller:而@Autowired和@Resource是用来修饰字段.构造函数或者设置方法,并做注入的. 2.当注解作用在类上时,表明这些类是交给spring容器进行管理的,而当使用@Autowired和@Resource时,表明我需要某个属性.方法或字段,但是并不需要我自己去new一个,只需要使用注解, spring容器会自动的将我需要的属性.方法或对象创造…
在阅读Spring Boot源码时,看到Spring Boot中大量使用ImportBeanDefinitionRegistrar来实现Bean的动态注入.它是Spring中一个强大的扩展接口.本篇文章来讲讲它相关使用. Spring Boot中的使用 在Spring Boot 内置容器的相关自动配置中有一个ServletWebServerFactoryAutoConfiguration类.该类的部分代码如下: @Configuration(proxyBeanMethods = false) @…
在Spring中使用Quartz有两种方式实现:第一种是任务类继承QuartzJobBean,第二种则是在配置文件里定义任务类和要执行的方法,类和方法可以是普通类.很显然,第二种方式远比第一种方式来的灵活. 测试环境 Spring3 M2 quartz-2.1.7 我们要达到这样的效果 public class CancelUnpaidOrderTask implements Job { @Autowired private AppOrderService orderService; @Over…
前言:Spring Boot配置文件值的注入有两种方式,分别是 @ConfigurationProperties @Value 这里我们使用第一种 首先我们创建一个application.yml文件,里面写入这样一组数据 person: lastName: hello age: 18 boss: false birth: 2017/12/12 maps: {k1: v1,k2: 12} lists: - lisi - zhaoliu dog: name: 小狗 age: 12 之后我们创建一个J…
0 引言 在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率. 以下列举几个手写API 文档的痛点: 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时. 接口返回结果不明确 不能直接在线测试接口,通常需要使用工具,比如postman 接口文档太多,不好管理 Swagger也就是为了解决这个问题,当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强. 1…