【问题标题】:In spring, is there a way to autowire the first bean?在春天,有没有办法自动装配第一个 bean?
【发布时间】:2016-06-03 07:20:10
【问题描述】:

在下面的例子中,有没有办法避免执行 context.getBean()? testService 随后使用的所有其他 bean 都会自动装配。 (它是一个控制台应用程序)

public class Test { 


        private static ITestService testService;

        private static ApplicationContext context;

           public static void main(String[] args) { 

            context = new ClassPathXmlApplicationContext(
                    new String[]{"/META-INF/spring/app-context.xml"});
            ITestService testService = context.getBean(ITestService.class); 

        }

}

我尝试向 ApplicationContext 添加 autowire 注释,但没有奏效。另外,如果我自动装配它,它如何知道我的 app-context.xml 的位置?

更新:我找到了我需要的东西over here

【问题讨论】:

  • 应用程序上下文不是常规 bean。实际上这个类包含所有其他 bean 定义。并且此类运行扫描 @Autowired 注释。那么,如果没有创建上下文,谁来扫描?
  • 看看@RunWith(SpringJUnit4ClassRunner.class)

标签: java spring spring-4


【解决方案1】:

是的,您在这里遗漏了一些细节。

下面是 Spring 工作原理的简短说明。

1- 应用程序上下文以某种方式加载(我们很快就会到达那里)。 2-加载后,应用上下文将初始化/创建所有定义的bean。这是 bean 作为依赖项注入的时候。在此之后,每当您从应用程序上下文中获取 bean 时,该 bean 都已初始化并准备好使用所有依赖项(考虑到一切正常)。

RE 第一步,有几种方法可以自动化 Spring 初始化。 一种方法是您正在做的事情,明确地实例化一个。其他方式可能是通过context listener,以防您在网络环境中,或者可能使用@RunWith。 (您可以找到更多here

就您而言,我相信您正在寻找在(单元?!?)测试环境中使用 Spring,因此您正在寻找类似

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {

    @Autowired
    private ApplicationContext applicationContext;

    // class body...
}

更多详情here

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#testing

【讨论】:

    【解决方案2】:

    如果不先初始化应用程序上下文,就不能调用 bean。 其次,在您的情况下,Test 类应该是 bean 本身,由 spring 管理,然后自动装配ITestService。应用程序上下文作为容器的目的是管理 bean 生命周期,因此您需要首先通过 ClassPathXmlApplicationContext 对其进行初始化,然后它将初始化您在您的 xml 文件中声明的所有 bean。关于避免 getBean 方法,如果您使用 servlet 创建 Web 应用程序,您可以避免使用 getBean。如果不是,您应该手动处理它。

    【讨论】:

      【解决方案3】:

      我同意@Desorder 所说的。当我开始使用@RunWith(SpringJUnit4ClassRunner.class) 和@ContextConfiguration 时,我曾经让我的测试用例工作。但是我花了一些时间来了解这两个在内部是如何工作的以及它们的默认配置。

      如果您想采取一些不同的方法并且想尝试不使用@RunWith 和@ContextConfiguration,请查看链接 - TUTORIAL: JUNIT @RULE. 有了这个,您将非常清楚提供了哪些 spring xml 文件位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-08
        • 2019-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-10
        • 2016-09-30
        相关资源
        最近更新 更多