介绍
@Profile元注解是在不同的生产环境中,@Bean创建的SpringBean根据spring.profiles.active指定的环境不同创建不同环境的bean对象
一.@Profile元注解需要配合spring.profiles.active一起使用
二.首先在resources下创建三个配置文件
application.properties:
spring.profiles.active=prod
其他两个配置文件创建了就行!
三.创建需要注入的实体类
package com.wzq.dome.entity;
import lombok.Data;
/**
* @description:
* @author: Wzq
* @create: 2019-12-12 15:00
*/
@Data
public class ProFileEntity {
private String name;
}
四.根据spring.profiles.active指定不同的环境选择注入的bean
DomeApplication:代码如下
package com.wzq;
import com.wzq.dome.entity.ProFileEntity;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
@SpringBootApplication
public class DomeApplication {
public static void main(String[] args) {
SpringApplication.run(DomeApplication.class, args);
}
@Bean(name = "proFileEntity")
@Profile("prod")
public ProFileEntity proFileEntity1(){
ProFileEntity proFileEntity = new ProFileEntity();
proFileEntity.setName("GoslingWu");
return proFileEntity;
}
@Bean(name = "proFileEntity")
@Profile("dev")
public ProFileEntity proFileEntity(){
ProFileEntity proFileEntity = new ProFileEntity();
proFileEntity.setName("wzq");
return proFileEntity;
}
}
五.使用
package com.wzq.dome.action;
import com.wzq.dome.entity.ProFileEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description:
* @author: Wzq
* @create: 2019-12-12 10:27
*/
@RestController
public class TestController {
@Autowired
ProFileEntity proFileEntity;
@RequestMapping("/test")
public String test(){
return proFileEntity.getName();
}
}