Add autowiring+AOP support to injected components

This commit is contained in:
Kelven Yang 2012-11-02 14:49:32 -07:00
parent cea8f3bf37
commit 0e9924fcee
3 changed files with 43 additions and 2 deletions

View File

@ -20,6 +20,7 @@ package com.cloud.utils.component;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@ -53,15 +54,24 @@ public class ComponentContext implements ApplicationContextAware {
assert(s_appContext != null);
return (T)s_appContext.getBean(beanType);
}
public static<T> T inject(Class<T> clz) {
T instance = s_appContext.getAutowireCapableBeanFactory().createBean(clz);
return inject(instance);
}
public static<T> T inject(Object instance) {
// autowire dynamically loaded object
AutowireCapableBeanFactory beanFactory = s_appContext.getAutowireCapableBeanFactory();
beanFactory.autowireBean(instance);
Advisor advisor = new DefaultPointcutAdvisor(new MatchAnyMethodPointcut(),
new TransactionContextBuilder());
ProxyFactory pf = new ProxyFactory();
pf.setTarget(instance);
pf.addAdvisor(advisor);
return (T)pf.getProxy();
return (T)pf.getProxy();
}
}

View File

@ -18,6 +18,7 @@ package com.cloud.utils.db;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import junit.framework.Assert;
@ -29,6 +30,8 @@ import org.springframework.stereotype.Component;
public class DbAnnotatedBase {
private static final Logger s_logger = Logger.getLogger(DbAnnotatedBase.class);
@Inject DummyComponent _dummy;
@PostConstruct
public void initTest() {
Assert.assertTrue(true);
@ -36,5 +39,6 @@ public class DbAnnotatedBase {
public void MethodWithClassDbAnnotated() {
s_logger.info("called");
_dummy.sayHello();
}
}

View File

@ -0,0 +1,27 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
import org.springframework.stereotype.Component;
@Component
public class DummyComponent {
public void sayHello() {
System.out.println("Hello, world");
}
}