springBoot中实现自定义属性配置、实现异步调用、多环境配置

本文介绍 Spring Boot 中自定义参数配置的方法,包括通过 application.properties 添加自定义属性并在 Bean 类中加载,以及如何实现异步调用和多环境配置。

springBoot中其他相关:

1:springBoot中自定义参数:

 

1-1、自定义属性配置:

 

在application.properties中除了可以修改默认配置,我们还可以在这配置自定义的属性,并在实体bean中加载出来。

 

1、在application.properties中添加自定义属性配置

 

com.demo.name = demo

com.demo.age = 11

com.demo.desc = magical demo

 

 

2、编写Bean类,加载属性

 

下面的Demo类需要添加@Component注解,让spring在启动的时候扫描到该类,并添加到spring容器中。

 

第一种:使用spring支持的@Value()加载

 

package com.sam.demo.conf;

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

@Component
public class Demo {

    //获取application.properties的属性
    @Value("${com.demo.name}")
    private String name;

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

    @Value("${com.demo.desc}")
    private String desc;
    
    //getter & setter 。。。。。。。
}

 

 

第二种:使用@ConfigurationProperties(prefix="") 设置前缀,属性上不需要添加注解。

 

 1 package com.sam.demo.conf;
 2 
 3 import org.springframework.stereotype.Component;
 4 
 9 @Component
10 @ConfigurationProperties(prefix = "com.demo") //配置文件的前缀
11 public class Demo {
12 
13     private String name;
14 
15     private int age;
16 
17     private String desc;
18 
19     //getter & setter..........
20 }

 

 

3、在controller中注入并使用Demo这个Bean。

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class IndexController {

    @Autowired
    private Demo demo;

    @RequestMapping("/index")
    public String index() {
        System.out.println(demo.getName() + " " + demo.getAge() + " " + demo.getDesc());
        return "index";
    }

}

 参考:

 https://www.jianshu.com/p/57e8554b691e

浏览器访问:http://localhost:8080/index ,控制台正常打印出demo的内容。

 

2-1:   springBoot中实现异步调用:

    使用@Async实现异步调用:

   启动类加上@EnableAsync ,需要执行异步方法上加入  @Async

 

 

 

 


 

 

3-1: 多环境配置:

 1:在resource包下面新建下面4个配置文件:

application.properties : 主配置文件

application-dev.properties:开发环境 application-test.properties:测试环境 application-prod.properties:生产环境

2:使用:

         在  application.properties  中添加 :     spring.profiles.active=prod  或   test   或  dev   实现不同启动环境配置。

                     


 

 

转载于:https://www.cnblogs.com/dw3306/p/9623837.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值