spring boot 注解

spring boot 注解

@Value

注入Spring boot application.properties配置的属性的值。

示例:

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
spring:
application:
name: mytest
mandatory-file-encoding: UTF-8
http:
encoding:
enabled: true
charset: utf-8
server:
port: 9090
myConfig:
myObject:
myName: zhangshan
myAge: 20

MyController

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
@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class MyController {
@Value("${myConfig.myObject.myName}")
private String myName;
@Value("${myConfig.myObject.myAge}")
private int myAge;
@RequestMapping(value = "/person",method = RequestMethod.GET)
public Person getPerson() {
Person person = new Person();
person.setId(25);
person.setName("张三");
person.setBirthday(new Date());
System.out.println(myName);
System.out.println(myAge);
return person;
}
}

@Configuration

相当于传统的xml配置文件,如果有些第三方库需要用到xml文件,建议仍然通过@Configuration类作为项目的配置主类——可以使用@ImportResource注解加载xml配置文件。

示例:

MyConfigBean

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
public class MyConfigBean {
@Value("${myConfig.myObject.myName}")
private String myName;
@Value("${myConfig.myObject.myAge}")
private int myAge;
public String getMyName() {
return myName;
}
public void setMyName(String myName) {
this.myName = myName;
}
public int getMyAge() {
return myAge;
}
public void setMyAge(int myAge) {
this.myAge = myAge;
}
}

MyConfig

1
2
3
4
5
6
7
8
@Configuration
public class MyConfig {
@Bean
public MyConfigBean myConfigBean() {
return new MyConfigBean();
}
}

MyController

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
@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class MyController {
@Value("${myConfig.myObject.myName}")
private String myName;
@Value("${myConfig.myObject.myAge}")
private int myAge;
@Autowired
private MyConfig myConfig;
@RequestMapping(value = "/person",method = RequestMethod.GET)
public Person getPerson() {
Person person = new Person();
person.setId(25);
person.setName("张三");
person.setBirthday(new Date());
System.out.println(myName);
System.out.println(myAge);
System.out.println("==================");
System.out.println(myConfig.myConfigBean().getMyName());
System.out.println(myConfig.myConfigBean().getMyAge());
return person;
}
}