springboot配置

1、@SpringBootApplication 包含哪些主要註解?
① @Configuration :可以和@Bean一起創建一個簡單的spring配置類(java),用來代替相應的xml配置文件


@Configuration  
public class Conf {  
 @Bean  
 public Car car() {  
      Car car = new Car();  
      car.setWheel(wheel());  
        return car;  
}  
 @Bean   
 public Wheel wheel() {  
return new Wheel();  
  }  



@Configuration 的註解類標識這個類可以使用spring ioc 容器作爲bean定義的來源。
@Bean註解的方法將返回一個對象,註冊在spring應用程序上下文中的bean


②@EnableAutoConfiguration :能夠自動配置spring的上下文
③@ComponentScan : 會自動掃描指定包下標有 @Component的類,註冊成bean,當然包括
@ComponentScan下的子註解 @Service @ Repository @Controller


2、application.properties(yml)可以放置在jar包內和jar包外的哪些目錄?
  jar包外:resources/config 和 resources
 jar包內:config包內和Classpath根目錄。WEB-INF/classes ,WEB-INF/classes 也就是classpath,資源目錄,客 戶端不能訪問。
按照優先級排序爲resources/config,resources,Classpath/config,Classpath。resource會覆蓋
classpath中相同的屬性。
如果相同優先級,application.properties 和application.yml,則application.yml會覆蓋
application.properties裏的屬性


3、Profile 多環境配置
不同的運行環境,往往需要不同的配置
在Spring Boot中多環境配置文件名需要滿足application-{profile}.properties的格式,其中{profile}對應你的環境標識,比如:
application-dev.properties:開發環境
application-prod.properties:生產環境
只需要在application.properties中使用spring.profiles.active屬性來設置,值對應上面提到的{profile},這裏就是指dev、prod這2個。
當然你也可以用命令行啓動的時候帶上參數:
java -jar xxx.jar --spring.profiles.active=dev
我給不同的環境添加不同的端口屬性server.port,然後根據指定不同的spring.profiles.active來切換使用。


4、自定義屬性
application.properties 可以把一些常量配置在這裏
比如:com.dd = "www"
使用:
通過@Value(value="{config.name}")就可以綁定到你想要的屬性上面
比如:
@Value=(value="{com.dd}")
private String dd;
屬性如果太多,可以綁定對象,使用註解@ConfigurationProperties(prefix="com.wjk")來指明
例如:wjk.java
@ConfigurationProperties(prefix="com.wjk")
public class wjk{
private String name;
private String no;
//getter和setter省略
}
然後,還需要在springboot入口類加上@EnableConfigurationProperties 並指明加載哪個bean


@SpringBootApplication
@EnableConfigurationProperties({wjk.class})
public class Chapter2Application {


    public static void main(String[] args) {
        SpringApplication.run(Chapter2Application.class, args);
    }
}
最後可以直接引用


@RestController
public class UserController {
    @Autowired
    wjk wjk;


    @RequestMapping("/")
    public String hexo(){
        return wjk.getName()+wjk.getNo();
    }
}


導入
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章