Solo  当前访客:3 开始使用

Spring的应用上下文


一、可以有多个上下文
image.png
Servlet WebApplicationContext继承了Root WebApplicationContext

二、业务增强的影响范围
当我们把增强放在Servlet WebApplicationContext时,在容器Root WebApplicationContext增强就会无效。
演示:

@AllArgsConstructor
@Slf4j
//需要增强的对象
public class TestBean {
    private String context;

    public void hello() {
        log.info("hello " + context);
    }
}
@Aspect
@Slf4j
//当TestBean的hello方法执行后,在继续执行printAfter
public class FooAspect {
    @AfterReturning("bean(testBean*)")
    public void printAfter() {
        log.info("after hello()");
    }
}
@Configuration
@EnableAspectJAutoProxy
//配置,演示不同上下文的效果
public class FooConfig {
    @Bean
    public TestBean testBeanX() {
        return new TestBean("foo");
    }

    @Bean
    public TestBean testBeanY() {
        return new TestBean("foo");
    }

    @Bean
    public FooAspect fooAspect() {
        return new FooAspect();
    }
}

//通过xml配置bean

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <aop:aspectj-autoproxy/>

    <bean id="testBeanX" class="geektime.spring.web.context.TestBean">
        <constructor-arg name="context" value="Bar" />
    </bean>

   <!-- <bean id="fooAspect" class="geektime.spring.web.foo.FooAspect" />-->
</beans>
@SpringBootApplication
@Slf4j
public class ContextHierarchyDemoApplication implements ApplicationRunner {

	public static void main(String[] args) {
		SpringApplication.run(ContextHierarchyDemoApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		ApplicationContext fooContext = new AnnotationConfigApplicationContext(FooConfig.class);
		ClassPathXmlApplicationContext barContext = new ClassPathXmlApplicationContext(
				new String[] {"applicationContext.xml"}, fooContext);
		TestBean bean = fooContext.getBean("testBeanX", TestBean.class);
		bean.hello();

		log.info("=============");

		bean = barContext.getBean("testBeanX", TestBean.class);
		bean.hello();

		bean = barContext.getBean("testBeanY", TestBean.class);
		bean.hello();
	}
}

结果:
当使用FooConfig的fooAspect时候,在xml文件中加上aop:aspectj-autoproxy/后,每个bean都能得到增强,去掉aop:aspectj-autoproxy/后,testBeanX增强失效,当注释掉FooConfig的fooAspect,使用xml的fooAspect时,则只有testBeanX增强有效。

0 0