利用Spring底层组件进行开发 (三层组件)
- 能够供我们使用的组件,都是Aware的子接口,即XxxxAware
以ApplicationContextAware为例:
- 实现步骤
-
a、实现ApplicationContextAware(译:发现 应用程序上下文),
-
b、重写其中的方法,都包含了一个对象。只需要将该对象 赋值到属性中即可
-
有什么用:例如ApplicationContextAware,可以通过该接口 获取到Ioc容器对象。
-
执行时间: 如果在main()中new Ioc容器: 先执行ApplicationContextAware实现类中的方法,通过该方法传入IoC容器 供我们自己使用; 然后再将该容器通过new返回给用户,因此拿到的是同一个IOC容器
-
BeanNameAware(译:发现 Bean的名):
-
@Component("myCom")
public class MyComponent implements ApplicationContextAware , BeanNameAware {
private ApplicationContext applicationContext;
private String beanName ;
// 容器在初始化时,发现是ApplicationContextAware 子接口 会自动注入
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
// 与 new 的ioc 容器是 同 一个 对象
}
@Override
public void setBeanName(String s) {
// 参数为当前bean的id值
this.beanName = s;
}
}
环境切换:@Profile
激活方式一:
- -Dspring.profiles.active=@Profile环境名
- 例如: -Dspring.profiles.active=myApple
- 联想:Mybatis切换数据库环境
@Profile("myApple") @Bean("apple") public Fruit apple(){ return new Apple(); } @Profile("myOrage") @Bean public Fruit orage(){ return new Orage(); }
激活方式二 :硬编码
有一个坑 : 错误方式
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
ConfigurableEnvironment environment = context.getEnvironment();
environment.setActiveProfiles("myApple");
其中AnnotationConfigApplicationContext中有一个refresh()操作:会将我们设置的一些参数还原
流程:没激活 | -> 进行激活 -> 刷新 -> 没激活
- 什么时候设置 ?
- 保存点 | : 配置类的编写处
- IoC容器在使用时必须refresh() ;如果是有参构造,内部已经刷新;如果无参构造,需要手工刷新。
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
//获取环境
ConfigurableEnvironment environment = context.getEnvironment();
//配置环境参数
environment.setActiveProfiles("myApple");
//保存点
context.register(MyConfig.class);
//刷新(由源码知,后接源码)
context.refresh();
String[] beanDefinitionNames = context.getBeanDefinitionNames();//获取容器中所有的bean 的id
Spring源码
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();//实例化
register(annotatedClasses);//加载配置类
refresh();//刷新
}