下面列出了org.springframework.context.event.test.TestEvent#org.springframework.tests.sample.beans.ITestBean 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Check that a transaction is created and committed.
*/
@Test
public void transactionShouldSucceedWithNotNew() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(getNameMethod, txatt);
TransactionStatus status = mock(TransactionStatus.class);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
// expect a transaction
given(ptm.getTransaction(txatt)).willReturn(status);
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
// verification!?
itb.getName();
checkTransactionStatus(false);
verify(ptm).commit(status);
}
@Test
public void testInterceptorInclusionMethods() {
class MyInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
throw new UnsupportedOperationException();
}
}
NopInterceptor di = new NopInterceptor();
NopInterceptor diUnused = new NopInterceptor();
ProxyFactory factory = new ProxyFactory(new TestBean());
factory.addAdvice(0, di);
assertThat(factory.getProxy(), instanceOf(ITestBean.class));
assertTrue(factory.adviceIncluded(di));
assertTrue(!factory.adviceIncluded(diUnused));
assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 1);
assertTrue(factory.countAdvicesOfType(MyInterceptor.class) == 0);
factory.addAdvice(0, diUnused);
assertTrue(factory.adviceIncluded(diUnused));
assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 2);
}
@Test
public void testLookupWithProxyInterfaceAndDefaultObject() throws Exception {
JndiObjectFactoryBean jof = new JndiObjectFactoryBean();
TestBean tb = new TestBean();
jof.setJndiTemplate(new ExpectedLookupTemplate("foo", tb));
jof.setJndiName("myFoo");
jof.setProxyInterface(ITestBean.class);
jof.setDefaultObject(Boolean.TRUE);
try {
jof.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testReentrance() {
int age1 = 33;
TestBean target1 = new TestBean();
ProxyFactory pf1 = new ProxyFactory(target1);
NopInterceptor di1 = new NopInterceptor();
pf1.addAdvice(0, di1);
ITestBean advised1 = (ITestBean) createProxy(pf1);
advised1.setAge(age1); // = 1 invocation
advised1.setSpouse(advised1); // = 2 invocations
assertEquals("one was invoked correct number of times", 2, di1.getCount());
assertEquals("Advised one has correct age", age1, advised1.getAge()); // = 3 invocations
assertEquals("one was invoked correct number of times", 3, di1.getCount());
// = 5 invocations, as reentrant call to spouse is advised also
assertEquals("Advised spouse has correct age", age1, advised1.getSpouse().getAge());
assertEquals("one was invoked correct number of times", 5, di1.getCount());
}
@Test
public void testCanPreventCastToAdvisedUsingOpaque() {
TestBean target = new TestBean();
ProxyFactory pc = new ProxyFactory(target);
pc.setInterfaces(new Class<?>[] {ITestBean.class});
pc.addAdvice(new NopInterceptor());
CountingBeforeAdvice mba = new CountingBeforeAdvice();
Advisor advisor = new DefaultPointcutAdvisor(new NameMatchMethodPointcut().addMethodName("setAge"), mba);
pc.addAdvisor(advisor);
assertFalse("Opaque defaults to false", pc.isOpaque());
pc.setOpaque(true);
assertTrue("Opaque now true for this config", pc.isOpaque());
ITestBean proxied = (ITestBean) createProxy(pc);
proxied.setAge(10);
assertEquals(10, proxied.getAge());
assertEquals(1, mba.getCalls());
assertFalse("Cannot be cast to Advised", proxied instanceof Advised);
}
@Test
public void testCanGetStaticPartFromJoinPoint() {
final Object raw = new TestBean();
ProxyFactory pf = new ProxyFactory(raw);
pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
pf.addAdvice(new MethodBeforeAdvice() {
@Override
public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
StaticPart staticPart = AbstractAspectJAdvice.currentJoinPoint().getStaticPart();
assertEquals("Same static part must be returned on subsequent requests", staticPart, AbstractAspectJAdvice.currentJoinPoint().getStaticPart());
assertEquals(ProceedingJoinPoint.METHOD_EXECUTION, staticPart.getKind());
assertSame(AbstractAspectJAdvice.currentJoinPoint().getSignature(), staticPart.getSignature());
assertEquals(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(), staticPart.getSourceLocation());
}
});
ITestBean itb = (ITestBean) pf.getProxy();
// Any call will do
itb.getAge();
}
@Test
public void testLookupWithProxyInterfaceAndDefaultObject() throws Exception {
JndiObjectFactoryBean jof = new JndiObjectFactoryBean();
TestBean tb = new TestBean();
jof.setJndiTemplate(new ExpectedLookupTemplate("foo", tb));
jof.setJndiName("myFoo");
jof.setProxyInterface(ITestBean.class);
jof.setDefaultObject(Boolean.TRUE);
try {
jof.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
@Test
public void testMatches() {
TestBean target = new TestBean();
target.setAge(27);
NopInterceptor nop = new NopInterceptor();
ControlFlowPointcut cflow = new ControlFlowPointcut(One.class, "getAge");
ProxyFactory pf = new ProxyFactory(target);
ITestBean proxied = (ITestBean) pf.getProxy();
pf.addAdvisor(new DefaultPointcutAdvisor(cflow, nop));
// Not advised, not under One
assertEquals(target.getAge(), proxied.getAge());
assertEquals(0, nop.getCount());
// Will be advised
assertEquals(target.getAge(), new One().getAge(proxied));
assertEquals(1, nop.getCount());
// Won't be advised
assertEquals(target.getAge(), new One().nomatch(proxied));
assertEquals(1, nop.getCount());
assertEquals(3, cflow.getEvaluations());
}
@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);
}
@Test
public void burlapProxyFactoryBeanWithAuthenticationAndAccessError() throws Exception {
BurlapProxyFactoryBean factory = new BurlapProxyFactoryBean();
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.setUsername("test");
factory.setPassword("bean");
factory.setOverloadEnabled(true);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
exception.expect(RemoteAccessException.class);
bean.setName("test");
}
@Test
public void burlapProxyFactoryBeanWithCustomProxyFactory() throws Exception {
TestBurlapProxyFactory proxyFactory = new TestBurlapProxyFactory();
BurlapProxyFactoryBean factory = new BurlapProxyFactoryBean();
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.setProxyFactory(proxyFactory);
factory.setUsername("test");
factory.setPassword("bean");
factory.setOverloadEnabled(true);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
assertEquals(proxyFactory.user, "test");
assertEquals(proxyFactory.password, "bean");
assertTrue(proxyFactory.overloadEnabled);
exception.expect(RemoteAccessException.class);
bean.setName("test");
}
@Test
public void testWithIntroduction() {
String beanName = "foo";
TestBean target = new RequiresBeanNameBoundTestBean(beanName);
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorIntroducingNamedBean(beanName));
ITestBean proxy = (ITestBean) pf.getProxy();
assertTrue("Introduction was made", proxy instanceof NamedBean);
// Requires binding
proxy.getAge();
NamedBean nb = (NamedBean) proxy;
assertEquals("Name returned correctly", beanName, nb.getBeanName());
}
@Test
public void testLookupWithProxyInterfaceAndLazyLookup() throws Exception {
JndiObjectFactoryBean jof = new JndiObjectFactoryBean();
final TestBean tb = new TestBean();
jof.setJndiTemplate(new JndiTemplate() {
@Override
public Object lookup(String name) {
if ("foo".equals(name)) {
tb.setName("tb");
return tb;
}
return null;
}
});
jof.setJndiName("foo");
jof.setProxyInterface(ITestBean.class);
jof.setLookupOnStartup(false);
jof.afterPropertiesSet();
assertTrue(jof.getObject() instanceof ITestBean);
ITestBean proxy = (ITestBean) jof.getObject();
assertNull(tb.getName());
assertEquals(0, tb.getAge());
proxy.setAge(99);
assertEquals("tb", tb.getName());
assertEquals(99, tb.getAge());
}
protected void doTestAspectsAndAdvisorAreApplied(ApplicationContext ac, ITestBean shouldBeWeaved) {
TestBeanAdvisor tba = (TestBeanAdvisor) ac.getBean("advisor");
MultiplyReturnValue mrv = (MultiplyReturnValue) ac.getBean("aspect");
assertEquals(3, mrv.getMultiple());
tba.count = 0;
mrv.invocations = 0;
assertTrue("Autoproxying must apply from @AspectJ aspect", AopUtils.isAopProxy(shouldBeWeaved));
assertEquals("Adrian", shouldBeWeaved.getName());
assertEquals(0, mrv.invocations);
assertEquals(34 * mrv.getMultiple(), shouldBeWeaved.getAge());
assertEquals("Spring advisor must be invoked", 2, tba.count);
assertEquals("Must be able to hold state in aspect", 1, mrv.invocations);
}
/**
* The instances are equal, but do not have object identity.
* Interceptors and interfaces and the target are the same.
*/
@Test
public void testSingletonInstancesAreEqual() {
ITestBean test1 = (ITestBean) factory.getBean("test1");
ITestBean test1_1 = (ITestBean) factory.getBean("test1");
//assertTrue("Singleton instances ==", test1 == test1_1);
assertEquals("Singleton instances ==", test1, test1_1);
test1.setAge(25);
assertEquals(test1.getAge(), test1_1.getAge());
test1.setAge(250);
assertEquals(test1.getAge(), test1_1.getAge());
Advised pc1 = (Advised) test1;
Advised pc2 = (Advised) test1_1;
assertArrayEquals(pc1.getAdvisors(), pc2.getAdvisors());
int oldLength = pc1.getAdvisors().length;
NopInterceptor di = new NopInterceptor();
pc1.addAdvice(1, di);
assertArrayEquals(pc1.getAdvisors(), pc2.getAdvisors());
assertEquals("Now have one more advisor", oldLength + 1, pc2.getAdvisors().length);
assertEquals(di.getCount(), 0);
test1.setAge(5);
assertEquals(test1_1.getAge(), test1.getAge());
assertEquals(di.getCount(), 3);
}
/**
* Check that the introduction advice isn't allowed to introduce interfaces
* that are unsupported by the IntroductionInterceptor.
*/
@Test
public void testCannotAddIntroductionAdviceWithUnimplementedInterface() throws Throwable {
TestBean target = new TestBean();
target.setAge(21);
ProxyFactory pc = new ProxyFactory(target);
try {
pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), ITestBean.class));
fail("Shouldn't be able to add introduction advice introducing an unimplemented interface");
}
catch (IllegalArgumentException ex) {
//assertTrue(ex.getMessage().indexOf("ntroduction") > -1);
}
// Check it still works: proxy factory state shouldn't have been corrupted
ITestBean proxied = (ITestBean) createProxy(pc);
assertEquals(target.getAge(), proxied.getAge());
}
@Test
public void testProxyAProxyWithAdditionalInterface() {
ITestBean target = new TestBean();
mockTargetSource.setTarget(target);
AdvisedSupport as = new AdvisedSupport();
as.setTargetSource(mockTargetSource);
as.addAdvice(new NopInterceptor());
as.addInterface(Serializable.class);
CglibAopProxy cglib = new CglibAopProxy(as);
ITestBean proxy1 = (ITestBean) cglib.getProxy();
mockTargetSource.setTarget(proxy1);
as = new AdvisedSupport(new Class<?>[]{});
as.setTargetSource(mockTargetSource);
as.addAdvice(new NopInterceptor());
cglib = new CglibAopProxy(as);
ITestBean proxy2 = (ITestBean) cglib.getProxy();
assertTrue(proxy2 instanceof Serializable);
}
@Test
public void setPropertyValuesIgnoresInvalidNestedOnRequest() {
ITestBean target = new TestBean();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("name", "rod"));
pvs.addPropertyValue(new PropertyValue("graceful.rubbish", "tony"));
pvs.addPropertyValue(new PropertyValue("more.garbage", new Object()));
AbstractPropertyAccessor accessor = createAccessor(target);
accessor.setPropertyValues(pvs, true);
assertTrue("Set valid and ignored invalid", target.getName().equals("rod"));
try {
// Don't ignore: should fail
accessor.setPropertyValues(pvs, false);
fail("Shouldn't have ignored invalid updates");
}
catch (NotWritablePropertyException ex) {
// OK: but which exception??
}
}
private long testRepeatedAroundAdviceInvocations(String file, int howmany, String technology) {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);
StopWatch sw = new StopWatch();
sw.start(howmany + " repeated around advice invocations with " + technology);
ITestBean adrian = (ITestBean) bf.getBean("adrian");
assertTrue(AopUtils.isAopProxy(adrian));
assertEquals(68, adrian.getAge());
for (int i = 0; i < howmany; i++) {
adrian.getAge();
}
sw.stop();
System.out.println(sw.prettyPrint());
return sw.getLastTaskTimeMillis();
}
private void testNamedPointcuts(Object aspectInstance) {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspectInstance, "someBean")),
ITestBean.class);
assertEquals("Around advice must apply", -1, itb.getAge());
assertEquals(realAge, target.getAge());
}
/**
* There are times when we want to call proceed() twice.
* We can do this if we clone the invocation.
*/
@Test
public void testCloneInvocationToProceedThreeTimes() throws Throwable {
TestBean tb = new TestBean();
ProxyFactory pc = new ProxyFactory(tb);
pc.addInterface(ITestBean.class);
MethodInterceptor twoBirthdayInterceptor = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
// Clone the invocation to proceed three times
// "The Moor's Last Sigh": this technology can cause premature aging
MethodInvocation clone1 = ((ReflectiveMethodInvocation) mi).invocableClone();
MethodInvocation clone2 = ((ReflectiveMethodInvocation) mi).invocableClone();
clone1.proceed();
clone2.proceed();
return mi.proceed();
}
};
@SuppressWarnings("serial")
StaticMethodMatcherPointcutAdvisor advisor = new StaticMethodMatcherPointcutAdvisor(twoBirthdayInterceptor) {
@Override
public boolean matches(Method m, @Nullable Class<?> targetClass) {
return "haveBirthday".equals(m.getName());
}
};
pc.addAdvisor(advisor);
ITestBean it = (ITestBean) createProxy(pc);
final int age = 20;
it.setAge(age);
assertEquals(age, it.getAge());
// Should return the age before the third, AOP-induced birthday
assertEquals(age + 2, it.haveBirthday());
// Return the final age produced by 3 birthdays
assertEquals(age + 3, it.getAge());
}
@Test
public void testSubclassMatching() {
TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.tests.sample.beans.ITestBean+");
assertTrue("Must match: in package", tpcf.matches(TestBean.class));
assertTrue("Must match: in package", tpcf.matches(ITestBean.class));
assertTrue("Must match: in package", tpcf.matches(CountingTestBean.class));
assertFalse("Must be excluded: not subclass", tpcf.matches(IOther.class));
assertFalse("Must be excluded: not subclass", tpcf.matches(DefaultListableBeanFactory.class));
}
@Test
public void testAutoProxyCreatorWithFallbackToTargetClass() {
StaticApplicationContext sac = new StaticApplicationContext();
sac.registerSingleton("testAutoProxyCreator", FallbackTestAutoProxyCreator.class);
sac.registerSingleton("noInterfaces", NoInterfaces.class);
sac.registerSingleton("containerCallbackInterfacesOnly", ContainerCallbackInterfacesOnly.class);
sac.registerSingleton("singletonNoInterceptor", TestBean.class);
sac.registerSingleton("singletonToBeProxied", TestBean.class);
sac.registerPrototype("prototypeToBeProxied", TestBean.class);
sac.refresh();
MessageSource messageSource = (MessageSource) sac.getBean("messageSource");
NoInterfaces noInterfaces = (NoInterfaces) sac.getBean("noInterfaces");
ContainerCallbackInterfacesOnly containerCallbackInterfacesOnly =
(ContainerCallbackInterfacesOnly) sac.getBean("containerCallbackInterfacesOnly");
ITestBean singletonNoInterceptor = (ITestBean) sac.getBean("singletonNoInterceptor");
ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied");
ITestBean prototypeToBeProxied = (ITestBean) sac.getBean("prototypeToBeProxied");
assertFalse(AopUtils.isCglibProxy(messageSource));
assertTrue(AopUtils.isCglibProxy(noInterfaces));
assertTrue(AopUtils.isCglibProxy(containerCallbackInterfacesOnly));
assertFalse(AopUtils.isCglibProxy(singletonNoInterceptor));
assertFalse(AopUtils.isCglibProxy(singletonToBeProxied));
assertFalse(AopUtils.isCglibProxy(prototypeToBeProxied));
TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator");
assertEquals(0, tapc.testInterceptor.nrOfInvocations);
singletonNoInterceptor.getName();
assertEquals(0, tapc.testInterceptor.nrOfInvocations);
singletonToBeProxied.getAge();
assertEquals(1, tapc.testInterceptor.nrOfInvocations);
prototypeToBeProxied.getSpouse();
assertEquals(2, tapc.testInterceptor.nrOfInvocations);
}
private void doTestTwoAdviceAspectWith(String location) {
ClassPathXmlApplicationContext bf = newContext(location);
boolean aspectSingleton = bf.isSingleton("aspect");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
testPrototype(adrian1, 0);
ITestBean adrian2 = (ITestBean) bf.getBean("adrian");
assertNotSame(adrian1, adrian2);
testPrototype(adrian2, aspectSingleton ? 2 : 0);
}
@Test
public void simpleBeanConfigured() throws Exception {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(
new ClassPathResource("simplePropertyNamespaceHandlerTests.xml", getClass()));
ITestBean rob = (TestBean) beanFactory.getBean("rob");
ITestBean sally = (TestBean) beanFactory.getBean("sally");
assertEquals("Rob Harrop", rob.getName());
assertEquals(24, rob.getAge());
assertEquals(rob.getSpouse(), sally);
}
@Test
public void testGetsAreNotTransactionalWithProxyFactory2DynamicProxy() {
this.factory.preInstantiateSingletons();
ITestBean testBean = (ITestBean) factory.getBean("proxyFactory2DynamicProxy");
assertTrue("testBean is a dynamic proxy", Proxy.isProxyClass(testBean.getClass()));
assertTrue(testBean instanceof TransactionalProxy);
doTestGetsAreNotTransactional(testBean);
}
@Test
public void testAspectsAreApplied() {
ClassPathXmlApplicationContext bf = newContext("aspects.xml");
ITestBean tb = (ITestBean) bf.getBean("adrian");
assertEquals(68, tb.getAge());
MethodInvokingFactoryBean factoryBean = (MethodInvokingFactoryBean) bf.getBean("&factoryBean");
assertTrue(AopUtils.isAopProxy(factoryBean.getTargetObject()));
assertEquals(68, ((ITestBean) factoryBean.getTargetObject()).getAge());
}
@Test
@SuppressWarnings("deprecation")
public void simpleHessianServiceExporter() throws IOException {
final int port = SocketUtils.findAvailableTcpPort();
TestBean tb = new TestBean("tb");
SimpleHessianServiceExporter exporter = new SimpleHessianServiceExporter();
exporter.setService(tb);
exporter.setServiceInterface(ITestBean.class);
exporter.setDebug(true);
exporter.prepare();
HttpServer server = HttpServer.create(new InetSocketAddress(port), -1);
server.createContext("/hessian", exporter);
server.start();
try {
HessianClientInterceptor client = new HessianClientInterceptor();
client.setServiceUrl("http://localhost:" + port + "/hessian");
client.setServiceInterface(ITestBean.class);
//client.setHessian2(true);
client.prepare();
ITestBean proxy = ProxyFactory.getProxy(ITestBean.class, client);
assertEquals("tb", proxy.getName());
proxy.setName("test");
assertEquals("test", proxy.getName());
}
finally {
server.stop(Integer.MAX_VALUE);
}
}
@Test
public void testProxyFactory2Lazy() {
ITestBean testBean = (ITestBean) factory.getBean("proxyFactory2Lazy");
assertFalse(factory.containsSingleton("target"));
assertEquals(666, testBean.getAge());
assertTrue(factory.containsSingleton("target"));
}
@Test
public void testNoIntroduction() {
String beanName = "foo";
TestBean target = new RequiresBeanNameBoundTestBean(beanName);
ProxyFactory pf = new ProxyFactory(target);
pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorWithoutIntroduction(beanName));
ITestBean proxy = (ITestBean) pf.getProxy();
assertFalse("No introduction", proxy instanceof NamedBean);
// Requires binding
proxy.getAge();
}