Spring Framework

@Profile

Restrict bean registration to a matching profile condition. Spring 7.0.9 instructional lab; source-reviewed, not executed.

Formal Syntax & Structure

java syntaxjava
@Profile("lab")

Working Example

Example Snippetjava
package lab.spring;import java.util.Map;import org.springframework.beans.factory.ObjectProvider;import org.springframework.context.annotation.*;import org.springframework.core.env.Environment;import org.springframework.core.env.MapPropertySource;public class ScopeDemo {    record Label(String text) {}    static class Draft {}    record Factory(ObjectProvider<Draft> drafts) {        Draft next() { return drafts.getObject(); }    }    static class Resource {        public void start() { System.out.println("start"); }        public void stop() { System.out.println("stop"); }    }    @Configuration(proxyBeanMethods = false)    static class Config {        @Bean @Profile("lab") Label label(Environment env) {            return new Label(env.getRequiredProperty("lab.label"));        }        @Bean @Scope("prototype") Draft draft() { return new Draft(); }        @Bean Factory factory(ObjectProvider<Draft> drafts) { return new Factory(drafts); }        @Bean(initMethod="start", destroyMethod="stop") @Lazy        Resource resource() { return new Resource(); }    }    public static void main(String[] args) {        try (var context = new AnnotationConfigApplicationContext()) {            context.getEnvironment().setActiveProfiles("lab");            context.getEnvironment().getPropertySources().addFirst(                new MapPropertySource("lab-only", Map.of("lab.label", "warehouse")));            context.register(Config.class);            context.refresh();            var label = context.getBean(Label.class);            var factory = context.getBean(Factory.class);            System.out.println("same=" + (label == context.getBean(Label.class)));            System.out.println("fresh=" + (factory.next() != factory.next()));            System.out.println("label=" + label.text());            context.getBean(Resource.class);        }    }}
Java Reference