一、spring-application-context
ApplicationContext接口由BeanFactory接口派生而来,提供了更多面向实际的功能。
ApplicationContext继承了HierachicalBeanFactory和ListableBeanFactory接口,在此基础上,还通过其他接口扩展了BeanFactory的功能。
下面通过aop和application context展示父子context不同之处
1. 上下文实例化
# 父context使用注解配置上下文
AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext(TestConfig.class);
# 子context使用xml配置上下文
ClassPathXmlApplicationContext childContext = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"}, parentContext);
2. aspect声明
@Aspect
@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TestAspect {
private String context;
@AfterReturning("bean(testBean*)")
public void afterReturning() {
log.info("aspect {}: after hello!", context);
}
}
3. 被增强的类
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class TestBean {
private String context;
public void hello() {
log.info("hello, {}", context);
}
}
4. 注解实例化bean对象
@Configuration
@EnableAspectJAutoProxy
public class TestConfig {
@Bean
public TestBean testBeanX() {
return new TestBean("testBeanX AnnotationConfigApplicationContext");
}
@Bean
public TestBean testBeanY() {
return new TestBean("testBeanY AnnotationConfigApplicationContext");
}
@Bean
public TestAspect testAspect() {
return new TestAspect("TestAspect AnnotationConfigApplicationContext");
}
}
5. xml配置实例化bean对象
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean id="testBeanX" class="com.example.springcontext.TestBean">
<constructor-arg name="context" value="testBeanX ClassPathXmlApplicationContext" />
</bean>
<bean id="testAspect" class="com.example.springcontext.TestAspect">
<constructor-arg name="context" value="TestAspect ClassPathXmlApplicationContext" />
</bean>
6. 测试
TestBean bean = parentContext.getBean("testBeanX", TestBean.class);
bean.hello();
log.info("-------------------");
bean = childContext.getBean("testBeanX", TestBean.class);
bean.hello();
log.info("-------------------");
bean = childContext.getBean("testBeanY", TestBean.class);
bean.hello();
调试不同配置,可得 aop 增强只会对在其所声明的上下文中的bean起作用。
源码
二、关于上下⽂常⽤的接⼝
BeanFactory
- DefaultListableBeanFactory
ApplicationContext
- ClassPathXmlApplicationContext
- FileSystemXmlApplicationContext
- AnnotationConfigApplicationContext
WebApplicationContext
web上下文层次
web配置方式
servlet3.0非配置方式