@Profile注解的使用——阅读开源项目中的代码

作用:指定Bean加载的生产环境

例子1:

 

//建立Bean实体
public class DemoBean {

    private String content;

    public DemoBean(String content) {
        super();
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}


=====================================
//使用@Configuration,区分不同的生产环境
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * Created by sang on 16-12-13.
 */
@Configuration
public class ProfileConfig {
    @Bean
    @Profile("dev")
    public DemoBean devDemoBean() {
        return new DemoBean("dev");
    }

    @Bean
    @Profile("prod")
    public DemoBean prodDemoBean() {
        return new DemoBean("prod");
    }
}

==========================
//设置生产环境,注册主配置类
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by sang on 16-12-13.
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
     context.getEnvironment().setActiveProfiles("prod");
      context.register(ProfileConfig.class
); context.refresh(); DemoBean bean = context.getBean(DemoBean.class); System.out.println(bean.getContent()); context.close(); } }

 

 

 

使用方法:

参考博客:https://blog.csdn.net/weixin_43108539/article/details/90044758?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

posted @ 2020-05-22 10:36  怪兽不纯粹  阅读(159)  评论(0)    收藏  举报