假如我们自己的组件需要使用 ApplicationContext 等,我们可以通过实现 XXXAware 接口来实现
@Component
public class TestCompent implements ApplicationContextAware, BeanNameAware {
private ApplicationContext applicationContext;
@Override
public void setBeanName(String name) {
System.out.println("current bean name is :【" + name + "】");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
扩展: @Profile 注解
通过@Profile 注解,根据环境来激活标识不同的 Bean
- @Profile 标识在类上,那么只有当前环境匹配,整个配置类才会生效
- @Profile 标识在 Bean 上 ,那么只有当前环境的 Bean 才会被激活;没有标志为@Profile 的 bean 不管 在什么环境都可以被激活
@Configuration
@PropertySource(value = {"classpath:ds.properties"})
public class MainConfig implements EmbeddedValueResolverAware {
@Value("${ds.username}")
private String userName;
@Value("${ds.password}")
private String password;
private String jdbcUrl;
private String classDriver;
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.jdbcUrl = resolver.resolveStringValue("${ds.jdbcUrl}");
this.classDriver = resolver.resolveStringValue("${ds.classDriver}");
}//标识为测试环境才会被装配 @Bean @Profile(value = "test") public DataSource testDs() { return buliderDataSource(new DruidDataSource()); }//标识开发环境才会被激活 @Bean @Profile(value = "dev") public DataSource devDs() { return buliderDataSource(new DruidDataSource()); }//标识生产环境才会被激活 @Bean @Profile(value = "prod")
public DataSource prodDs() { return buliderDataSource(new DruidDataSource()); }
private DataSource buliderDataSource(DruidDataSource dataSource) {
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setDriverClassName(classDriver);
dataSource.setUrl(jdbcUrl);
return dataSource;
} }
激活切换环境的方法
- 方法一:通过运行时 jvm 参数来切换 -Dspring.profiles.active=test|dev|prod
-
方法二:通过代码的方式来激活
image.png
网友评论