1. 程式人生 > 其它 >springboot 修改屬性配置的三種方法

springboot 修改屬性配置的三種方法


一、修改預設配置
例1、spring boot 開發web應用的時候,預設tomcat的啟動埠為8080,如果需要修改預設的埠,則需要在application.properties 新增以下記錄:
server.port=8888
二、自定義屬性配置
在application.properties中除了可以修改預設配置,我們還可以在這配置自定義的屬性,並在實體bean中加載出來。
1、在application.properties中新增自定義屬性配置
com.sam.name=sam
com.sam.age=11
com.sam.desc=magical sam
2、編寫Bean類,載入屬性
Sam類需要新增@Component註解,讓spring在啟動的時候掃描到該類,並新增到spring容器中。
第一種:使用spring支援的@Value()載入
package com.sam.demo.conf;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
* @author sam
* @since 2017/7/15
*/
@Component
public class Sam {

//獲取application.properties的屬性
@Value("${com.sam.name}")
private String name;

@Value("${com.sam.age}")
private int age;

@Value("${com.sam.desc}")
private String desc;

//getter & setter
}
第二種:使用@ConfigurationProperties(prefix="") 設定字首,屬性上不需要添加註解。
package com.sam.demo.conf;

import org.springframework.stereotype.Component;

/**
* @author sam
* @since 2017/7/15
*/
@Component
@ConfigurationProperties(prefix = "com.sam")
public class Sam {

private String name;

private int age;

private String desc;

//getter & setter
}
三、自定義配置類
在Spring Boot框架中,通常使用@Configuration註解定義一個配置類,Spring Boot會自動掃描和識別配置類,從而替換傳統Spring框架中的XML配置檔案。

當定義一個配置類後,還需要在類中的方法上使用@Bean註解進行元件配置,將方法的返回物件注入到Spring容器中,並且元件名稱預設使用的是方法名,
這裡使用DataSource舉例
package com.example.demo.config;
import javax.sql.DataSource;
@Slf4j
@Configuration
@EnableConfigurationProperties(JdbcPro.class)
public class DataSouce1Config {
@Value("${my.name}")
private String name ;
@Value("${spring.datasource.url}")
private String dbUrl;

@Value("${spring.datasource.username}")
private String username;

@Value("${spring.datasource.password}")
private String password;

@Value("${spring.datasource.driver-class-name}")
private String driverClassName;


@Bean
@Primary
public DataSource dataSource(){

DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(this.dbUrl);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
druidDataSource.setDriverClassName(driverClassName);
log.info("cccccccccccccccc");
log.info(this.name);
return druidDataSource;
}

}

Spring Boot 屬性配置&自定義屬性配置
參考:https://www.cnblogs.com/williamjie/p/9258186.html