Finology 大数据金融

通过大数据以量化金融

我们使用 @Autowired 注解来注入依赖,下面通过代码,来简单演示一下其最基础的注入逻辑。

这里我将创建一个新的注解 @MyAutowired

MyAutowired.java

1
2
3
4
5
6
7
8
9
10
package gy.finolo.autowireddemo;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
@Documented
public @interface MyAutowired {
}

一个 Service 实现类,里面没有任何方法,主要用于测试。

UserService.java

1
2
3
4
5
package gy.finolo.autowireddemo;

public class UserService {
}

一个 Controller 类,我们把上面的 Service 类注入此类中。测试 main 方法也在这里面,方便测试。

UserController.java

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
package gy.finolo.autowireddemo;


import java.util.stream.Stream;

public class UserController {

@MyAutowired
private UserService userService;

public static void main(String[] args) {

UserController userController = new UserController();
Class<? extends UserController> clazz = userController.getClass();
Stream.of(clazz.getDeclaredFields()).forEach(field -> {
// check the member variable whether annotated with @MyAutowired
MyAutowired annotation = field.getAnnotation(MyAutowired.class);
if (annotation != null) {
field.setAccessible(true);
// get the class type of the field
Class<?> type = field.getType();
try {
Object o = type.newInstance();
field.set(userController, o);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}

}
});

System.out.println(userController.userService);
}
}

运行后,可以看到非 null 的输出,证明已经成功把 UserService 依赖注入。

Springboot 版本 2.1.5.RELEASE

引用的 spring-boot-starter-test 版本为:2.1.2.RELEASE

依赖的 junit 版本为 4.12

必须要按如下写注解,才可以把类注入成功。

1
2
3
4
5
6
7
8
9
10
11
12
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootApplication.class)
public class ControllerTests {

@Autowired
private UserController userController;

@Test
public void test() {
System.out.println(userController);
}
}
  • 需要写 @RunWith 注解
  • @SpringBootTest 注解需要添加 classes 属性,值为启动类的 class 对象。
  • test() 方法必须为 public

上述几点在新版本的 Springboot 中(比如2.2及以上)可能有变化。

对于这个充分和必要条件,现在梳理一下。

如果 A => B 且 A </= B,即如果 A 能推出 B,且 B 不能推出 A,则 A 是 B 的充分(不必要)条件。

如果 A =/> B 且 A <= B,即如果 A 不能推出 B,且 B 能推出 A,则 A 是 B 的必要(不充分)条件。

可微条件

必要条件

即可微,能推出什么。

若函数在某点可微分,则函数在该点必连续;

若二元函数在某点可微分,则该函数在该点对x和y的偏导数必存在。

充分条件

即什么能推出可微。

若函数对x和y的偏导数在这点的某一邻域内都存在,且均在这点连续,则该函数在这点可微。

0%