springboot 常量类配置

作者: 殷天文 | 来源:发表于2018-03-19 18:26 被阅读186次
1.先引入maven依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
2.新建一个Java类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 常量类
 * 
 */
@Configuration
@ConfigurationProperties(prefix = "constant")
@PropertySource("classpath:constant.properties")
public class Constant {

    private String name;

    private String sex;

   //省略get set toString
}

prefix代表属性文件中的前缀,@PropertySource指定加载的那个属性文件,如是默认的application.properties 则不用指定。

    //加载多个文件
    @PropertySource({    
        "classpath:config.properties",    
        "classpath:db.properties" //如果是相同的key,则最后一个起作用    
    })

springboot 1.5以后的版本,不支持@ConfigurationProperties(prefix = "config2",locations="classpath:test.properties") locations这种写法,使用@PropertySource

3.新建constant.properties
constant.name=taven
constant.sex=male
4.在启动类添加@EnableConfigurationProperties 指定
@SpringBootApplication
@EnableConfigurationProperties(Constant.class)
public class CommunicateApplication {

    public static void main(String[] args) {
        SpringApplication.run(CommunicateApplication.class, args);
    }
    
}

使用时,通过依赖注入得到单例

    @Autowired
    private Constant constant;

相关文章

网友评论

  • michael7520:无法获取取YML文件格式的属性值吗???
    如:
    constant:
    name: michael
    sex: male

本文标题:springboot 常量类配置

本文链接:https://www.haomeiwen.com/subject/zkwpqftx.html