Spring @Profile注解

本文介绍如何在Spring中使用Profile配置来根据不同环境加载相应的配置文件。通过@Profile注解实现开发和生产环境中Bean的选择性实例化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 通过设定Enviroment的ActiveProfiles来决定当前context需要使用的配置环境,在开发中使用@Profile注解类或方法达到在不同情况下选择实例化不同的Bean
  2. 通过设定jvm的spring.profiles.active参数来设置环境
  3. Web项目设置servlet的context.paramter中
<!-- servlet2.5及以下 -->
<servlet>
    <init-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>production</param-value>
    </init-param>
</servlet>
/**
 * servlet3.0及以上
 */
public class WebInit implements WebApplicationInitializer{
    @Override
    public void onStartup(ServletContext contailer)throws ServletException{
        container.setInitParameter("spring.profiles.default","dev");
    }
}

示例Bean

/**
 * @author Kevin
 * @description
 * @date 2016/6/30
 */
public class DemoBean {
    private String content;

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

    public String getContent() {
        return content;
    }

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

Profile配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * @author Kevin
 * @description
 * @date 2016/6/30
 */
@Configuration
public class ProfileConfig {

    @Bean
    // Profile为dev时实例化devDemoBean
    @Profile("dev")
    public DemoBean devDemoBean(){
        return new DemoBean("from development profile");
    }

    @Bean
    // Profile为prod时实例化prodDemoBean
    @Profile("prod")
    public DemoBean prodDemoBean(){
        return new DemoBean("from production profile");
    }
}

运行

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author Kevin
 * @description
 * @date 2016/6/30
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 将profile设置为prod
        context.getEnvironment().setActiveProfiles("prod");
        // 注册Bean配置类
        context.register(ProfileConfig.class);
        // 刷新容器
        context.refresh();
        DemoBean demoBean = context.getBean(DemoBean.class);
        System.out.println(demoBean.getContent());
        context.close();
    }
}

结果

输出:from production profile

转载于:https://my.oschina.net/kevinair/blog/703244

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值