org.mockito.InjectMocks#org.springframework.aop.framework.Advised源码实例Demo

下面列出了org.mockito.InjectMocks#org.springframework.aop.framework.Advised 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test
public void testSerializable() throws Exception {
	DerivedTestBean tb = new DerivedTestBean();
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setInterfaces(ITestBean.class);
	ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor();
	proxyFactory.addAdvice(cti);
	proxyFactory.setTarget(tb);
	ITestBean proxy = (ITestBean) proxyFactory.getProxy();
	proxy.getAge();

	ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy);
	Advised advised = (Advised) serializedProxy;
	ConcurrencyThrottleInterceptor serializedCti =
			(ConcurrencyThrottleInterceptor) advised.getAdvisors()[0].getAdvice();
	assertEquals(cti.getConcurrencyLimit(), serializedCti.getConcurrencyLimit());
	serializedProxy.getAge();
}
 
源代码2 项目: spring-analysis-note   文件: EnableAsyncTests.java
@Test
public void customAsyncAnnotationIsPropagated() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(CustomAsyncAnnotationConfig.class, CustomAsyncBean.class);
	ctx.refresh();

	Object bean = ctx.getBean(CustomAsyncBean.class);
	assertTrue(AopUtils.isAopProxy(bean));
	boolean isAsyncAdvised = false;
	for (Advisor advisor : ((Advised) bean).getAdvisors()) {
		if (advisor instanceof AsyncAnnotationAdvisor) {
			isAsyncAdvised = true;
			break;
		}
	}
	assertTrue("bean was not async advised as expected", isAsyncAdvised);

	ctx.close();
}
 
源代码3 项目: tcc-transaction   文件: SpringContextUtil.java
/**
 * 根据模块中的实例获取模块标识
 * @param target
 * @return
 */
public static String getModuleIdByTarget(Object target){
    if(target instanceof ModuleContextAdapter){
        return ((ModuleContextAdapter)target).getModuleContext().getModuleId();
    }
    //如果是Aop代理则需要获取targetClass的ClassLoader
    ClassLoader classLoader= target.getClass().getClassLoader();
    if(target instanceof Advised){
        classLoader= ((Advised)target).getTargetClass().getClassLoader();
    }
    for(ModuleContext each: moduleContexts.values()){
        if(each.getClassLoader()==classLoader){
            return each.getModuleId();
        }
    }
    return "webapplication";
}
 
源代码4 项目: spring-data-dev-tools   文件: JdbcFixture.java
private static void disableEntityCallbacks(ApplicationContext context) {
	
	JdbcBookRepository repository = context.getBean(JdbcBookRepository.class);

	Field field = ReflectionUtils.findField(SimpleJdbcRepository.class, "entityOperations");
	ReflectionUtils.makeAccessible(field);
	
	try {
		JdbcAggregateTemplate aggregateTemplate = (JdbcAggregateTemplate) ReflectionUtils.getField(field,
				((Advised) repository).getTargetSource().getTarget());

		field = ReflectionUtils.findField(JdbcAggregateTemplate.class, "publisher");
		ReflectionUtils.makeAccessible(field);
		ReflectionUtils.setField(field, aggregateTemplate, NoOpApplicationEventPublisher.INSTANCE);
		
		aggregateTemplate.setEntityCallbacks(NoOpEntityCallbacks.INSTANCE);
		
	} catch (Exception o_O) {
		throw new RuntimeException(o_O);
	}
}
 
@Test
public void testProgrammaticProxyCreation() {
	ITestBean testBean = new TestBean();

	AspectJProxyFactory factory = new AspectJProxyFactory();
	factory.setTarget(testBean);

	CounterAspect myCounterAspect = new CounterAspect();
	factory.addAspect(myCounterAspect);

	ITestBean proxyTestBean = factory.getProxy();

	assertTrue("Expected a proxy", proxyTestBean instanceof Advised);
	proxyTestBean.setAge(20);
	assertEquals("Programmatically created proxy shouldn't match bean()", 0, myCounterAspect.count);
}
 
源代码6 项目: sakai   文件: StatsUpdateManagerTest.java
@SuppressWarnings("unchecked")
@Test
public void testConfigIsEventContextSupported() throws Exception {
	// #3: EventContextSupported
	assertEquals(true, statsManager.isEventContextSupported());

	// make sure it processes both events
	Event e1 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/non_existent_site/resource_id", FakeData.SITE_A_ID, FakeData.USER_A_ID, "session-id-a");
	Event e2 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/"+FakeData.SITE_A_ID+"/resource_id", null, FakeData.USER_B_ID, "session-id-a");
	statsUpdateManager.collectEvents(Arrays.asList(e1, e2));
	List<EventStat> results1 = (List<EventStat>) db.getResultsForClass(EventStatImpl.class);
	assertEquals(2, results1.size());

	// none of these events will be picked up
	((StatsManagerImpl) ((Advised) statsManager).getTargetSource().getTarget()).setEventContextSupported(false);
	assertEquals(false, statsManager.isEventContextSupported());
	Event e3 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTREAD, "/content/group/non_existent_site/resource_id", FakeData.SITE_A_ID, FakeData.USER_A_ID, "session-id-a");
	Event e4 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/"+FakeData.SITE_B_ID+"/resource_id", null, FakeData.USER_B_ID, "session-id-a");
	statsUpdateManager.collectEvents(Arrays.asList(e3, e4));
	List<EventStat> results2 = (List<EventStat>) db.getResultsForClass(EventStatImpl.class);
	assertEquals(2, results2.size());
}
 
@Before
public void onSetUp() throws Exception {
	ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	AroundAdviceBindingTestAspect  aroundAdviceAspect = ((AroundAdviceBindingTestAspect) ctx.getBean("testAspect"));

	ITestBean injectedTestBean = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(injectedTestBean));

	this.testBeanProxy = injectedTestBean;
	// we need the real target too, not just the proxy...

	this.testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();

	mockCollaborator = mock(AroundAdviceBindingCollaborator.class);
	aroundAdviceAspect.setCollaborator(mockCollaborator);
}
 
源代码8 项目: spring-analysis-note   文件: BenchmarkTests.java
private long testBeforeAdviceWithoutJoinPoint(String file, int howmany, String technology) {
	ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);

	StopWatch sw = new StopWatch();
	sw.start(howmany + " repeated before advice invocations with " + technology);
	ITestBean adrian = (ITestBean) bf.getBean("adrian");

	assertTrue(AopUtils.isAopProxy(adrian));
	Advised a = (Advised) adrian;
	assertTrue(a.getAdvisors().length >= 3);
	assertEquals("adrian", adrian.getName());

	for (int i = 0; i < howmany; i++) {
		adrian.getName();
	}

	sw.stop();
	System.out.println(sw.prettyPrint());
	return sw.getLastTaskTimeMillis();
}
 
源代码9 项目: sakai   文件: StatsUpdateManagerTest.java
@SuppressWarnings("unchecked")
@Test
public void testConfigIsEventContextSupported() throws Exception {
	// #3: EventContextSupported
	assertEquals(true, statsManager.isEventContextSupported());

	// make sure it processes both events
	Event e1 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/non_existent_site/resource_id", FakeData.SITE_A_ID, FakeData.USER_A_ID, "session-id-a");
	Event e2 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/"+FakeData.SITE_A_ID+"/resource_id", null, FakeData.USER_B_ID, "session-id-a");
	statsUpdateManager.collectEvents(Arrays.asList(e1, e2));
	List<EventStat> results1 = (List<EventStat>) db.getResultsForClass(EventStatImpl.class);
	assertEquals(2, results1.size());

	// none of these events will be picked up
	((StatsManagerImpl) ((Advised) statsManager).getTargetSource().getTarget()).setEventContextSupported(false);
	assertEquals(false, statsManager.isEventContextSupported());
	Event e3 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTREAD, "/content/group/non_existent_site/resource_id", FakeData.SITE_A_ID, FakeData.USER_A_ID, "session-id-a");
	Event e4 = statsUpdateManager.buildEvent(new Date(), FakeData.EVENT_CONTENTNEW, "/content/group/"+FakeData.SITE_B_ID+"/resource_id", null, FakeData.USER_B_ID, "session-id-a");
	statsUpdateManager.collectEvents(Arrays.asList(e3, e4));
	List<EventStat> results2 = (List<EventStat>) db.getResultsForClass(EventStatImpl.class);
	assertEquals(2, results2.size());
}
 
@Test
public void serializable() throws Exception {
	TestBean1 tb = new TestBean1();
	CallCountingTransactionManager ptm = new CallCountingTransactionManager();
	AnnotationTransactionAttributeSource tas = new AnnotationTransactionAttributeSource();
	TransactionInterceptor ti = new TransactionInterceptor(ptm, tas);

	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setInterfaces(ITestBean1.class);
	proxyFactory.addAdvice(ti);
	proxyFactory.setTarget(tb);
	ITestBean1 proxy = (ITestBean1) proxyFactory.getProxy();
	proxy.getAge();
	assertEquals(1, ptm.commits);

	ITestBean1 serializedProxy = (ITestBean1) SerializationTestUtils.serializeAndDeserialize(proxy);
	serializedProxy.getAge();
	Advised advised = (Advised) serializedProxy;
	TransactionInterceptor serializedTi = (TransactionInterceptor) advised.getAdvisors()[0].getAdvice();
	CallCountingTransactionManager serializedPtm =
			(CallCountingTransactionManager) serializedTi.getTransactionManager();
	assertEquals(2, serializedPtm.commits);
}
 
源代码11 项目: spring-analysis-note   文件: AopTestUtils.java
/**
 * Get the ultimate <em>target</em> object of the supplied {@code candidate}
 * object, unwrapping not only a top-level proxy but also any number of
 * nested proxies.
 * <p>If the supplied {@code candidate} is a Spring
 * {@linkplain AopUtils#isAopProxy proxy}, the ultimate target of all
 * nested proxies will be returned; otherwise, the {@code candidate}
 * will be returned <em>as is</em>.
 * @param candidate the instance to check (potentially a Spring AOP proxy;
 * never {@code null})
 * @return the target object or the {@code candidate} (never {@code null})
 * @throws IllegalStateException if an error occurs while unwrapping a proxy
 * @see Advised#getTargetSource()
 * @see org.springframework.aop.framework.AopProxyUtils#ultimateTargetClass
 */
@SuppressWarnings("unchecked")
public static <T> T getUltimateTargetObject(Object candidate) {
	Assert.notNull(candidate, "Candidate must not be null");
	try {
		if (AopUtils.isAopProxy(candidate) && candidate instanceof Advised) {
			Object target = ((Advised) candidate).getTargetSource().getTarget();
			if (target != null) {
				return (T) getUltimateTargetObject(target);
			}
		}
	}
	catch (Throwable ex) {
		throw new IllegalStateException("Failed to unwrap proxied object", ex);
	}
	return (T) candidate;
}
 
@Test
public void testSerializable() throws Exception {
	DerivedTestBean tb = new DerivedTestBean();
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setInterfaces(ITestBean.class);
	ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor();
	proxyFactory.addAdvice(cti);
	proxyFactory.setTarget(tb);
	ITestBean proxy = (ITestBean) proxyFactory.getProxy();
	proxy.getAge();

	ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy);
	Advised advised = (Advised) serializedProxy;
	ConcurrencyThrottleInterceptor serializedCti =
			(ConcurrencyThrottleInterceptor) advised.getAdvisors()[0].getAdvice();
	assertEquals(cti.getConcurrencyLimit(), serializedCti.getConcurrencyLimit());
	serializedProxy.getAge();
}
 
源代码13 项目: galaxy   文件: SpringContextUtil.java
/**
 * 根据模块中的实例获取模块标识
 * @param target
 * @return
 */
public static String getModuleIdByTarget(Object target){
    if(target instanceof ModuleContextAdapter){
        return ((ModuleContextAdapter)target).getModuleContext().getModuleId();
    }
    //如果是Aop代理则需要获取targetClass的ClassLoader
    ClassLoader classLoader= target.getClass().getClassLoader();
    if(target instanceof Advised){
        classLoader= ((Advised)target).getTargetClass().getClassLoader();
    }
    for(ModuleContext each: moduleContexts.values()){
        if(each.getClassLoader()==classLoader){
            return each.getModuleId();
        }
    }
    return "webapplication";
}
 
@Before
public void setup() throws Exception {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	testBeanProxy = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(testBeanProxy));

	// we need the real target too, not just the proxy...
	testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();

	AdviceBindingTestAspect beforeAdviceAspect = (AdviceBindingTestAspect) ctx.getBean("testAspect");

	mockCollaborator = mock(AdviceBindingCollaborator.class);
	beforeAdviceAspect.setCollaborator(mockCollaborator);
}
 
private MapTaskBatchDao getMapTaskBatchDao() throws Exception {
	Field taskExecutionDaoField = ReflectionUtils.findField(SimpleTaskExplorer.class,
			"taskExecutionDao");
	taskExecutionDaoField.setAccessible(true);

	MapTaskExecutionDao taskExecutionDao;

	if (AopUtils.isJdkDynamicProxy(this.taskExplorer)) {
		SimpleTaskExplorer dereferencedTaskRepository = (SimpleTaskExplorer) ((Advised) this.taskExplorer)
				.getTargetSource().getTarget();

		taskExecutionDao = (MapTaskExecutionDao) ReflectionUtils
				.getField(taskExecutionDaoField, dereferencedTaskRepository);
	}
	else {
		taskExecutionDao = (MapTaskExecutionDao) ReflectionUtils
				.getField(taskExecutionDaoField, this.taskExplorer);
	}

	return new MapTaskBatchDao(taskExecutionDao.getBatchJobAssociations());
}
 
@Before
public void onSetUp() throws Exception {
	ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	AroundAdviceBindingTestAspect  aroundAdviceAspect = ((AroundAdviceBindingTestAspect) ctx.getBean("testAspect"));

	ITestBean injectedTestBean = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(injectedTestBean));

	this.testBeanProxy = injectedTestBean;
	// we need the real target too, not just the proxy...

	this.testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();

	mockCollaborator = mock(AroundAdviceBindingCollaborator.class);
	aroundAdviceAspect.setCollaborator(mockCollaborator);
}
 
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
 	if (bean instanceof AopInfrastructureBean) {
		// Ignore AOP infrastructure such as scoped proxies.
		return bean;
	}
	Class<?> targetClass = AopUtils.getTargetClass(bean);
	if (AopUtils.canApply(this.advisor, targetClass)) {
		if (bean instanceof Advised) {
			((Advised) bean).addAdvisor(0, this.advisor);
			return bean;
		}
		else {
			ProxyFactory proxyFactory = new ProxyFactory(bean);
			// Copy our properties (proxyTargetClass etc) inherited from ProxyConfig.
			proxyFactory.copyFrom(this);
			proxyFactory.addAdvisor(this.advisor);
			return proxyFactory.getProxy(this.beanClassLoader);
		}
	}
	else {
		// No async proxy needed.
		return bean;
	}
}
 
源代码18 项目: spring-cloud-aws   文件: AmazonS3ClientFactory.java
private static AmazonS3Client getAmazonS3ClientFromProxy(AmazonS3 amazonS3) {
	if (AopUtils.isAopProxy(amazonS3)) {
		Advised advised = (Advised) amazonS3;
		Object target = null;
		try {
			target = advised.getTargetSource().getTarget();
		}
		catch (Exception e) {
			return null;
		}
		return target instanceof AmazonS3Client ? (AmazonS3Client) target : null;
	}
	else {
		return amazonS3 instanceof AmazonS3Client ? (AmazonS3Client) amazonS3 : null;
	}
}
 
@Test
public void testPerThisAspect() throws SecurityException, NoSuchMethodException {
	TestBean target = new TestBean();
	int realAge = 65;
	target.setAge(realAge);
	TestBean itb = (TestBean) createProxy(target,
			getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerThisAspect(), "someBean")),
			TestBean.class);
	assertEquals("Around advice must NOT apply", realAge, itb.getAge());

	Advised advised = (Advised) itb;
	// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
	assertEquals(4, advised.getAdvisors().length);
	ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia =
			(ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
	assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
	InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[2];
	LazySingletonAspectInstanceFactoryDecorator maaif =
			(LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory();
	assertFalse(maaif.isMaterialized());

	// Check that the perclause pointcut is valid
	assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
	assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut());

	// Hit the method in the per clause to instantiate the aspect
	itb.getSpouse();

	assertTrue(maaif.isMaterialized());

	assertTrue(imapa.getDeclaredPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getAge"), null));

	assertEquals("Around advice must apply", 0, itb.getAge());
	assertEquals("Around advice must apply", 1, itb.getAge());
}
 
源代码20 项目: sakai   文件: EventAggregatorTestPerf.java
@Before
public void onSetUp() throws Exception {
    db.deleteAll();
    memoryService.resetCachers();

    // Setup site users
    siteUsers = new ArrayList<>();
    IntStream.range(0, MAX_USERS).forEach(i -> siteUsers.add("user-" + i));
    siteResources = new ArrayList<>();
    IntStream.range(0, MAX_RESOURCES).forEach(i -> siteResources.add("/content/group/" + FakeData.SITE_A_ID + "/resource-" + i));

    when(contentTypeImageService.getContentTypeImage("folder")).thenReturn("sakai/folder.gif");
    when(contentTypeImageService.getContentTypeImage("image/png")).thenReturn("sakai/image.gif");

    FakeSite userSiteA = spy(FakeSite.class).set("~" + FakeData.USER_A_ID);
    userSiteA.setUsers(new HashSet<>(siteUsers));
    userSiteA.setMembers(new HashSet<>(siteUsers));
    when(siteService.getSiteUserId(FakeData.USER_A_ID)).thenReturn("~" + FakeData.USER_A_ID);
    when(siteService.getSiteUserId("no_user")).thenReturn(null);
    when(siteService.getSite("~" + FakeData.USER_A_ID)).thenReturn(userSiteA);

    // Site A has tools {SiteStats, Chat}, has {user-a,user-b}
    FakeSite siteA = spy(FakeSite.class).set(FakeData.SITE_A_ID, Arrays.asList(StatsManager.SITESTATS_TOOLID, FakeData.TOOL_CHAT, StatsManager.RESOURCES_TOOLID));
    siteA.setUsers(new HashSet<>(Arrays.asList(FakeData.USER_A_ID, FakeData.USER_B_ID)));
    siteA.setMembers(new HashSet<>(Arrays.asList(FakeData.USER_A_ID, FakeData.USER_B_ID)));
    when(siteService.getSite(FakeData.SITE_A_ID)).thenReturn(siteA);
    when(siteService.isUserSite(FakeData.SITE_A_ID)).thenReturn(false);
    when(siteService.isSpecialSite(FakeData.SITE_A_ID)).thenReturn(false);

    // This is needed to make the tests deterministic, otherwise on occasion the collect thread will run
    // and break the tests.
    statsUpdateManager.setCollectThreadEnabled(true);

    ((StatsManagerImpl) ((Advised) statsManager).getTargetSource().getTarget()).setShowAnonymousAccessEvents(true);
    ((StatsManagerImpl) ((Advised) statsManager).getTargetSource().getTarget()).setEnableSitePresences(true);
}
 
@Test
public void testSerializable() throws Throwable {
	testSets();
	// Count is now 2
	Person p2 = (Person) SerializationTestUtils.serializeAndDeserialize(proxied);
	NopInterceptor nop2 = (NopInterceptor) ((Advised) p2).getAdvisors()[0].getAdvice();
	p2.getName();
	assertEquals(2, nop2.getCount());
	p2.echo(null);
	assertEquals(3, nop2.getCount());
}
 
源代码22 项目: cxf   文件: SpringClassUnwrapper.java
@Override
public Object getRealObject(Object o) {
    if (o instanceof Advised) {
        try {

            Advised advised = (Advised)o;
            Object target = advised.getTargetSource().getTarget();
            //could be a proxy of a proxy.....
            return getRealObject(target);
        } catch (Exception ex) {
            // ignore
        }
    }
    return o;
}
 
@Test
public void testProxyingDecorator() throws Exception {
	ITestBean bean = (ITestBean) this.beanFactory.getBean("debuggingTestBean");
	assertTestBean(bean);
	assertTrue(AopUtils.isAopProxy(bean));
	Advisor[] advisors = ((Advised) bean).getAdvisors();
	assertEquals("Incorrect number of advisors", 1, advisors.length);
	assertEquals("Incorrect advice class", DebugInterceptor.class, advisors[0].getAdvice().getClass());
}
 
@Test
public void testNonMatchingBeanName() {
	assertFalse("Didn't expect a proxy", testBean3 instanceof Advised);

	testBean3.setAge(20);
	assertEquals(0, counterAspect.count);
}
 
@Before
public void setup() throws Exception {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());
	AdviceBindingTestAspect afterAdviceAspect = (AdviceBindingTestAspect) ctx.getBean("testAspect");

	testBeanProxy = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(testBeanProxy));

	// we need the real target too, not just the proxy...
	testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();

	mockCollaborator = mock(AdviceBindingCollaborator.class);
	afterAdviceAspect.setCollaborator(mockCollaborator);
}
 
@Test
public void testSessionScoping() throws Exception {
	MockHttpSession oldSession = new MockHttpSession();
	MockHttpSession newSession = new MockHttpSession();

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setSession(oldSession);
	RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

	ITestBean scoped = (ITestBean) this.context.getBean("sessionScoped");
	assertTrue("Should be AOP proxy", AopUtils.isAopProxy(scoped));
	assertFalse("Should not be target class proxy", scoped instanceof TestBean);

	ITestBean scopedAlias = (ITestBean) this.context.getBean("sessionScopedAlias");
	assertSame(scoped, scopedAlias);

	ITestBean testBean = (ITestBean) this.context.getBean("testBean");
	assertTrue("Should be AOP proxy", AopUtils.isAopProxy(testBean));
	assertFalse("Regular bean should be JDK proxy", testBean instanceof TestBean);

	String rob = "Rob Harrop";
	String bram = "Bram Smeets";

	assertEquals(rob, scoped.getName());
	scoped.setName(bram);
	request.setSession(newSession);
	assertEquals(rob, scoped.getName());
	request.setSession(oldSession);
	assertEquals(bram, scoped.getName());

	assertTrue("Should have advisors", ((Advised) scoped).getAdvisors().length > 0);
}
 
源代码27 项目: spring-analysis-note   文件: BenchmarkTests.java
private long testMix(String file, int howmany, String technology) {
	ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);

	StopWatch sw = new StopWatch();
	sw.start(howmany + " repeated mixed invocations with " + technology);
	ITestBean adrian = (ITestBean) bf.getBean("adrian");

	assertTrue(AopUtils.isAopProxy(adrian));
	Advised a = (Advised) adrian;
	assertTrue(a.getAdvisors().length >= 3);

	for (int i = 0; i < howmany; i++) {
		// Hit all 3 joinpoints
		adrian.getAge();
		adrian.getName();
		adrian.setAge(i);

		// Invoke three non-advised methods
		adrian.getDoctor();
		adrian.getLawyer();
		adrian.getSpouse();
	}

	sw.stop();
	System.out.println(sw.prettyPrint());
	return sw.getLastTaskTimeMillis();
}
 
private void checkAtAspectJAspect(String appContextFile) {
	ApplicationContext context = new ClassPathXmlApplicationContext(appContextFile, getClass());
	ICounter counter = (ICounter) context.getBean("counter");
	assertTrue("Proxy didn't get created", counter instanceof Advised);

	counter.increment();
	JoinPointMonitorAtAspectJAspect callCountingAspect = (JoinPointMonitorAtAspectJAspect)context.getBean("monitoringAspect");
	assertEquals("Advise didn't get executed", 1, callCountingAspect.beforeExecutions);
	assertEquals("Advise didn't get executed", 1, callCountingAspect.aroundExecutions);
}
 
@Test
public void testMatchingFactoryBeanObject() {
	assertTrue("Matching bean must be advised (proxied)", this.testFactoryBean1 instanceof Advised);
	assertEquals("myValue", this.testFactoryBean1.get("myKey"));
	assertEquals("myValue", this.testFactoryBean1.get("myKey"));
	assertEquals("Advice not executed: must have been", 2, this.counterAspect.getCount());
	FactoryBean<?> fb = (FactoryBean<?>) ctx.getBean("&testFactoryBean1");
	assertTrue("FactoryBean itself must *not* be advised", !(fb instanceof Advised));
}
 
@Test
public void testMatchingFactoryBeanItself() {
	assertTrue("Matching bean must *not* be advised (proxied)", !(this.testFactoryBean2 instanceof Advised));
	FactoryBean<?> fb = (FactoryBean<?>) ctx.getBean("&testFactoryBean2");
	assertTrue("FactoryBean itself must be advised", fb instanceof Advised);
	assertTrue(Map.class.isAssignableFrom(fb.getObjectType()));
	assertTrue(Map.class.isAssignableFrom(fb.getObjectType()));
	assertEquals("Advice not executed: must have been", 2, this.counterAspect.getCount());
}