springboot外部配置

1、常规属性配置
(1)在application.properties增加属性

server.port=9090
server.context-path=/helloboot

book.author=zxy
book.name=spring boot

(2)修改入口类

    @Value("${book.author}")
    private String author;
    @Value("${book.name}")
    private String name;

    @RequestMapping("/")
    String index(){
        return "hello Spring Boot"+author+" "+name;
    }

(3)访问http://localhost:9090/helloboot

hello Spring Bootzxy spring boot

2、(类型安全配置)基于properties
@Value注入在实际项目显得麻烦,配置通常是多个,
(1)添加配置,在项目资源路径下新建author.properties

author.name=zxy11
author.age=20

(2)新建包com.wisely.config,此包下新建类AuthorSettings
boot1.5以前添加文件是在@ConfigurationProperties里面的lications指定 ,这儿是1.5以上的版本,方法是在PropertySource指定

@Component
@PropertySource("classpath:author.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)检验代码

@SpringBootApplication
@RestController
public class ZXYApplication {

    @Autowired
    private AuthorSettings authorSettings;

    @RequestMapping("/")
    public String index(){
        return "author.getName()"+authorSettings.getName()+" author.getAge() "+authorSettings.getAge();
    }

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

(4)运行http://localhost:8080

author.getName()zxy11 author.getAge() 20
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值