Spring Boot配置及註解詳解
一般情況下,我們建立了一個Spring Boot程式之後,按照預設的配置就可以啟動了,但是我們還是可以自定義一些配置以及修改一些配置
一:多個環境的檔案配置
由於一個專案在開發的過程當中,需要經歷開發測試以及正式部署三個階段,我們可以根據不同的環境作不同的配置,配置的格式嚴格遵循下面的規則:application-{profile}.properties,其中{profile}對應你的環境標識。然後不同的配置檔案進行不同的配置,比如dev配置的埠號是8081,prod配置的埠號是8082,test配置的埠號是8083。
我們如何使用這三個檔案呢?只需要在application.yml檔案當中引入即可,按照下圖引入了dev的開發配置,執行程式,程式就會執行在8081埠。
在配置yml檔案的時候,出現了異常,最後排查發現:使用yml檔案格式進行配置的時候,冒號後面必須要有一個空格,否則執行出錯。
二:自定義一些屬性
比如我們需要在配置檔案當中儲存一些資訊,比如系統的預設登入賬號和預設的登入密碼,我們在application.yml檔案定義:
system:
login:
username: admin
password: 123456
@Value("${system.login.username}") private String username; @Value("${system.login.password}") private int password; @ResponseBody @RequestMapping("/info") public String getInfo(){ return username+":"+password; }
啟動工程,訪問:localhost:8018/info,瀏覽器顯示:
三:如何將配置檔案的屬性賦予給實體物件
我們在application.yml檔案當中配置一些屬性如下:
my:
name: king james
age: 33
number: ${random.int}
uuid: ${random.uuid}
max: ${random.int(10)}
value: ${random.value}
greeting: hi,i'm ${my.name}
建議與之對應的實體類
@ConfigurationProperties(prefix = "my") @Component//雖然不加沒事,但是最好加上,因為接下來用的時候IDEA不會報找不到類 public class Player { private String name; private int age; private int number; private String uuid; private int max; private String value; private String greeting; //省略set和get方法....
@Autowired
private Player player;
@ResponseBody
@RequestMapping("/player")
public String player(){
return JSON.toJSONString(player);
}
啟動工程,訪問:localhost:8018/player,瀏覽器顯示如下,說明已經正確的注入了對應的資料
在這當中遇到了兩個問題,首先在player類中彈出:Spring Boot Configuration Annotion Processor not found in classpath
解決這個問題,在pom檔案當中新增如下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
然後會出現:Re-run Spring Boot Configuration Annotation Processor to update generated metadata
這個問題可以忽略,不影響程式碼執行。只是提醒使用者,進行必要的重新編譯。
四:自定義一個配置檔案
比如我們不想把所有的配置資訊都寫在application.yml檔案當中,我們想單獨出一個檔案出來進行這些額外的配置,比如新建一個檔案text.properties,裡面加入如下配置資訊:
system.login.username=admin
system.login.password=123456
@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "system.login")
@Component
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@Autowired
private User user;
@ResponseBody
@RequestMapping("/user")
public String user(){
return JSON.toJSONString(user);
}
啟動工程,訪問:localhost:8018/user,瀏覽器顯示如下,說明已經正確的注入了對應的資料
五:Spring Boot常用註解
@SpingBootApplication:宣告這是一個SpringBoot的應用,放在主類上面
@SpringBootApplication
public class FourApplication {
public static void main(String[] args) {
SpringApplication.run(FourApplication.class, args);
}
}
@ComponentScan:自動掃描和裝配bean,一般用在主類上面
@Configuration:初始化一些配置,需要在專案當中進行很多初始化的工作,比如資料庫連線池等
@EnableTransactionManagement:開啟事務管理,然後訪問資料庫的Service方法上添加註解 @Transactional 便可
@MapperScan(value="com.xxx.xxx"):自動掃描某個包下面的dao檔案,這裡使用的是mybatis操作資料庫
@Configuration
@MapperScan("com.xxx.xxx.xxx")
@EnableTransactionManagement
public class DuridConfig implements EnvironmentAware {}
@EnableAutoConfiguration:自動初始化一些可能需要的配置和bean,一般放在主類上面
@Repository:新增在dao層,用於標註資料訪問元件
@Repository
public interface UserDao {
/**
* 用來儲存使用者資訊的方法
* @param user
*/
void save(User user);
}
@Service:用於標註業務層的元件
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void save(User user) {
userDao.save(user);
}
}
@Component:泛指元件,當這個元件不好歸類的時候使用
@ConfigurationProperties(prefix="xxx"):匯入配置 檔案當中的一些屬性
@Component
@ConfigurationProperties(prefix = "my")
public class Player {}
@Bean:宣告一個bean
@Bean
public JedisPool redisPoolFactory() {
logger.info("redis地址:" + host + ":" + port);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
jedisPoolConfig.setMinIdle(poolMinIdle);
//JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
logger.info("JedisPool注入成功!!");
return jedisPool;
}
@Controller:用於標註控制層元件
@ResponseBody:表示返回的結果直接寫入HTTP response body中
@RequestMapping(""/xxx):請求地址對映
@Autowired:自動注入bean
@Controller
public class HelloController {
@Autowired
private User user;
@ResponseBody
@RequestMapping("/user")
public String user(){
return JSON.toJSONString(user);
}
}
@RestController:相當於@[email protected]
@RestController
public class UserController {
@Autowired
private User user;
@RequestMapping("/user")
public String user(){
return JSON.toJSONString(user);
}
}
@RequestParam:用來處理Content-Type: 為 application/x-www-form-urlencoded
編碼的內容,提交方式GET、POST
@PathVariable:處理REST ful風格的URI時候使用
@RequestBody:該註解用來處理Content-Type: 為application/json, application/xml編碼的內容
@CookieValue:cookie裡面包含的資訊
@RequestHeader:請求頭裡面的資訊
@PostMapping:專門處理為Post請求, @RequestMapping(value = "/xxx",method = RequestMethod.POST)簡化版
@GetMapping:專門處理為Get請求, @RequestMapping(value = "/xxx",method = RequestMethod.Get)簡化版
@RestController
public class UserController {
@Autowired
private User user;
@GetMapping("/user1")
public String user1(@RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive")long keepAlive){
return JSON.toJSONString(user);
}
@PostMapping("/user2")
public String user2(@RequestParam Map<String, Object> params){
return JSON.toJSONString(user);
}
@PostMapping("/user3/{id}")
public String user3(@PathVariable("id")Integer id,@CookieValue("JSESSIONID") String cookie){
return JSON.toJSONString(user);
}
@PostMapping("/user4")
public String user4(@RequestBody(required = false) String requestJson){
return JSON.toJSONString(user);
}
}
@EnableScheduling:代表會去掃描帶有 @Scheduled(cron="0/10 * * * * ?")註解並執行,加在主類上面
@Scheduled(cron="0/10 * * * * ?"):定時器,按照cron規則執行的定時方法,標註在方法之上。