代码之家  ›  专栏  ›  技术社区  ›  Spencer Kormos

将bean注入Spring托管上下文之外的类

  •  52
  • Spencer Kormos  · 技术社区  · 17 年前

    我是我公司一种产品的最终用户。它不太适合集成到Spring中,但是我能够获得上下文的句柄并按名称检索所需的bean。然而,我仍然想知道是否可以将bean注入这个类,即使这个类不是由Spring本身管理的。

    澄清:管理某个类MyClass的生命周期的应用程序也在管理Spring上下文的生命周期。Spring不知道MyClass的实例,我想知道如何将实例提供给上下文,但无法在上下文本身中创建实例。

    7 回复  |  直到 17 年前
        1
  •  62
  •   David Tinker    16 年前

    您可以这样做:

    ApplicationContext ctx = ...
    YourClass someBeanNotCreatedBySpring = ...
    ctx.getAutowireCapableBeanFactory().autowireBeanProperties(
        someBeanNotCreatedBySpring,
        AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true);
    

    @Autowired 等等 YourClass

        2
  •  3
  •   Donal Fellows    12 年前

    尽管bean的制造是外部的,但将其引入Spring的一种方法是使用标记为 @Configuration 具有方法的bean(标记为 @Bean )这实际上会生成实例并通过Spring将其交回(此时Spring会执行其属性注入和代理生成)。

    prototype ,你会在每个地方得到一颗新鲜的豆子。

    @Configuration
    public class FooBarMaker {
        @Bean(autowire = Autowire.BY_TYPE)
        @Scope("prototype")
        public FooBar makeAFooBar() {
            // You probably need to do some more work in here, I imagine
            return new FooBar();
        }
    }
    

    @配置 豆(我使用它来创建接口实例,其中要实例化的类的名称是在运行时定义的。)

        3
  •  2
  •   Dave    12 年前
        4
  •  2
  •   alexbt    8 年前

    A、 B、C是spring管理的bean(由spring框架构建和管理) x、 y实际上是由应用程序构造的简单POJO,没有spring的帮助

    现在,如果您希望y使用spring获得对Z的引用,那么您需要有一个spring应用程序上下文的“句柄”

    一种方法是实施 ApplicationContextAware 界面在这种情况下,我建议A、B或C实现此接口,并将applicationContext引用存储在静态成员中。

    class C implmenets ApplicationContextAware{
        public static ApplicationContex ac;
         void setApplicationContext(ApplicationContext applicationContext)  {
                   ac = applicationContext;
         }
     .............
    }
    

    现在,在y班,你应该有:

    (Z)(C.ac.getBean("classZ")).doSomething()
    

    嗯——约纳坦

        5
  •  1
  •   keyser help    13 年前

    我希望它能帮助每个人,就像它最终帮助了我一样。

    Accessing Spring Beans from outside Spring Context

        7
  •  0
  •   GreenGiant WoodenKitty    12 年前

    并使该对象可用于注入到其他 this article .

    基本上,您创建一个父应用程序上下文,并将外部对象作为一个单例推送到该父上下文中。然后创建主应用程序上下文(例如,从xml文件),父应用程序上下文作为其父应用程序上下文。

    Object externalObject = ...
    GenericApplicationContext parent = new StaticApplicationContext();
    parent.getBeanFactory().registerSingleton( "externalObject", externalObject );
    parent.refresh();
    ApplicationContext appContext = new ClassPathXmlApplicationContext( ... , parent);