@Profile 注解的作用在不同的场景下,给出不同的类实例。比如在生产环境中给出的 DataSource 实例和测试环境给出的 DataSource 实例是不同的。
@Profile 的使用时,一般是在@Configuration 下使用,标注在类或者方法上,标注的时候填入一个字符串(例如”dev”),作为一个场景, 或者一个区分。在 Spring 中,配置 Profile 为 dev 时,就可以获取到这个 bean 了。
例子
比如,实现一个数据源,在 dev 环境和在 pro 环境下,返回的对象是不同的。
接口DataSource
package com.myjava.demo;
public interface DataSource {
public String name() ;
}
dev 的 DataSource 和 pro 的 DataSource 分别是 2 个不同的实现
表示dev环境的DataSource
package com.myjava.demo;
public class DataSourceDev implements DataSource {
public String mySource() {
return "这是dev";
}
}
表示pro环境的DataSource
package com.myjava.demo;
public class DataSourcePro implements DataSource {
public String mySource() {
return "这是pro";
}
}
使用了一个配置类,基于@Configuration 标注,配置里面,用了@Profile,分别表示了哪个对象作用于哪个环境
配置 。
package com.myjava.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class Config {
@Bean(name = "dataSource")
@Profile("dev")
public DataSource getDataSourceDev() {
return new DataSourceDev();
}
@Bean(name = "dataSource")
@Profile("pro")
public DataSource getDataSourcePro() {
return new DataSourcePro();
}
}
在 Main 方法中,调用 dataSource.mySource() 的时候,会根据设定的 ActiveProfiles 来匹配相应的对象。
Main方法
package com.myjava;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.myjava.demo.*;
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(Config.class);
context.getEnvironment().setActiveProfiles("dev");
context.refresh();
DataSource dataSource = (DataSource) context.getBean("dataSource");
System.out.println(dataSource.mySource());
context.close();
}
}
实际上,很少通过上面的方式激活 Spring 容器中的 Profile,通常都是让 Spring 容器自动去读取 Profile 的值,然后自动设置。这些实现通常是和具体框架实现,或者虚拟机参数,环境变量等相关。比如:作为 SpringMVC 中的 DispatcherServlet 的初始化参数,作为 Web 应用上下文中的初始化参数,或者使用@AtivceProfile 来进行激活。