Java

spring autowired为null问题解决

2022-08-10

Spring Autowired无法自动装载问题

如下代码在使用了ComponentAutowired注解后仍然不能自动装载, 具体代码如下

解决方法如下: 加上@SpringBootTest注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.baeldung.async;

import com.baeldung.async.config.SpringAsyncConfig;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ContextConfiguration(classes = {SpringAsyncConfig.class}, loader = AnnotationConfigContextLoader.class)
public class AsyncAnnotationExampleIntegrationTest {

@Autowired
private AsyncComponent asyncAnnotationExample;

// tests

@Test
public void testAsyncAnnotationForMethodsWithVoidReturnType() {
System.out.println("Start - invoking an asynchronous method. " + Thread.currentThread().getName());
asyncAnnotationExample.asyncMethodWithVoidReturnType();
System.out.println("End - invoking an asynchronous method. ");
}

@Test
public void testAsyncAnnotationForMethodsWithReturnType() throws InterruptedException, ExecutionException {
System.out.println("Start - invoking an asynchronous method. " + Thread.currentThread().getName());
final Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType();

while (true) {
if (future.isDone()) {
System.out.println("Result from asynchronous process - " + future.get());
break;
}
System.out.println("Continue doing something else. ");
Thread.sleep(1000);
}
}

@Test
public void testAsyncAnnotationForMethodsWithConfiguredExecutor() {
System.out.println("Start - invoking an asynchronous method . ");
asyncAnnotationExample.asyncMethodWithConfiguredExecutor();
System.out.println("End - invoking an asynchronous method. ");
}

@Test
public void testAsyncAnnotationForMethodsWithException() throws Exception {
System.out.println("Start - invoking an asynchronous method. ");
asyncAnnotationExample.asyncMethodWithExceptions();
System.out.println("End - invoking an asynchronous method. ");
}
}

参考

https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null

扫描二维码,分享此文章