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

原文地址:https://www.cnblogs.com/luckyna/p/15503260.html