SpringBoot中的注入
SpringBoot中提供了两种注入方式:注入基本属性
,对象注入
基本属性注入
首先要注入的属性上添加
@Value
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
50package com.buubiu.controller;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author buubiu
**/
public class HelloController {
private String name;
private int port;
private Date bir;
private String[] strs;
private List<String> lists;
private Map<String, String> maps;
public String hello() {
System.out.println("hello springboot");
System.out.println("name = " + name);
System.out.println("port = " + port);
System.out.println("bir = " + bir);
for (String str : strs) {
System.out.println("str = " + str);
}
lists.forEach(list-> System.out.println("list = " + list));
maps.forEach((k,v)-> System.out.println("k = " + k + " v = " + v));
return "hello springboot";
}
}其次要修改配置文件
application.properties
1
2
3
4
5name=buubiu
bir=2020/12/12 12:12:12
strs=aa,bb,cc,dd
lists=buubiu1,buubiu2,buubiu3
maps={'aa':'buubiu','bb':'buubiu2','cc':'buubiu3'}
对象方式注入
在对象类上加上注解
@Configuration或@Component 和 @ConfigurationProperties
User.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16package com.buubiu.entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author buubiu
**/
public class User {
private String id;
private Integer age;
...
}HelloController.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
26package com.buubiu.controller;
import com.buubiu.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author buubiu
**/
public class HelloController {
private User user;
public String hello() {
System.out.println("hello springboot");
System.out.println("user = " + user);
return "hello springboot";
}
}application.properties
1
2user.id=111
user.age=22
如若想在配置文件中有提示,可以添加下面依赖
1
2
3
4
5
6<!--构建元数据-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
SpringBoot中的注入