SpringBoot實戰學習(十) Spring Boot型別安全配置
阿新 • • 發佈:2019-01-31
1.目錄結構
2.編寫
1.application.properties 新增配置
author.name=wen
author.age=24
2.型別安全的Bean
package com.wen.springBoot.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
//載入properties檔案內的配置,通過prefix屬性指定properties的配置的字首
@ConfigurationProperties(prefix="author")
public class AuthorSettings {
private String name;
private Long age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
}
3.入口類
package com.wen.springBoot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework .web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wen.springBoot.config.AuthorSettings;
@RestController
//Spring Boot專案核心註解,開啟自動配置
//組合了@Configuration、@EnableAutoConfiguration、@ComponentScan
//@EnableAutoConfiguration讓Spring Boot根據類路徑jar包依賴為當前專案進行自動配置
//Spring Boot會自動掃描@SpringBootApplication所在類的同級包及下級包的Bean
@SpringBootApplication
public class DemoApplication {
//直接注入配置
@Autowired
private AuthorSettings authorSettings;
@RequestMapping("/")
String index(){
return "authorName:"+authorSettings.getName()+" authorAge:"+authorSettings.getName();
}
public static void main(String[] args) {//main方法,專案啟動入口
SpringApplication.run(DemoApplication.class, args);
}
}
3.執行
入口類→右鍵→Run As→Java Application 待專案部署, 訪問http://localhost:8080