DynamicClientFactoryBean.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package cn.nosum.support.config;
  2. import cn.nosum.support.proxy.InvocationHandlerFactory;
  3. import cn.nosum.support.proxy.Target;
  4. import org.springframework.beans.BeansException;
  5. import org.springframework.beans.factory.FactoryBean;
  6. import org.springframework.context.ApplicationContext;
  7. import org.springframework.context.ApplicationContextAware;
  8. import org.springframework.util.StringUtils;
  9. /**
  10. * Dynamic client factory bean.
  11. *
  12. * @author Young
  13. */
  14. public class DynamicClientFactoryBean implements FactoryBean<Object>, ApplicationContextAware {
  15. private ApplicationContext applicationContext;
  16. private String name;
  17. private Class<?> type;
  18. private String refName;
  19. private Class<?> refType;
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. public void setType(Class<?> type) {
  24. this.type = type;
  25. }
  26. public void setRefName(String refName) {
  27. this.refName = refName;
  28. }
  29. public void setRefType(Class<?> refType) {
  30. this.refType = refType;
  31. }
  32. @Override
  33. public Object getObject() throws Exception {
  34. return getTarget();
  35. }
  36. <T> T getTarget() {
  37. Targeter targeter = applicationContext.getBean(Targeter.class);
  38. InvocationHandlerFactory handlerFactory = applicationContext.getBean(InvocationHandlerFactory.class);
  39. if (!StringUtils.hasText(this.refName)){
  40. String[] beanNamesForType = applicationContext.getBeanNamesForType(this.refType);
  41. this.refName = beanNamesForType[0];
  42. }
  43. return (T) targeter.target(this, handlerFactory,new Target.DefaultTarget(this.name, this.type, this.refName, this.refType) );
  44. }
  45. @Override
  46. public Class<?> getObjectType() {
  47. return this.type;
  48. }
  49. @Override
  50. public boolean isSingleton() {
  51. return true;
  52. }
  53. @Override
  54. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  55. this.applicationContext = applicationContext;
  56. }
  57. }