使用SpringApplication时加载applicationcontext.xml

问题描述 投票:7回答:4

任何人都可以提供一个加载applicationContext.xml文件的SpringApplication示例吗?

我正在尝试使用Spring's Example(基于Gradle)将我的GWT RPC应用程序移动到RESTful Web服务。我有一个applicationContext.xml,但我没有看到如何让SpringApplication加载它。通过手动加载

ApplicationContext context = new ClassPathXmlApplicationContext(args);

导致空的背景。 ......即使它起作用,也会与返回的那个分开

SpringApplication.run(Application.class, args);

或者有没有办法让外部bean进入SpringApplication.run创建的应用程序上下文?

spring-boot applicationcontext
4个回答
11
投票

如果您想使用类路径中的文件,您可以随时执行此操作:

@SpringBootApplication
@ImportResource("classpath:applicationContext.xml")
public class ExampleApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(ExampleApplication.class, args);
    }
}

注意classpath注释中的@ImportResource字符串。


8
投票

您可以使用@ImportResource将XML配置文件导入Spring Boot应用程序。例如:

@SpringBootApplication
@ImportResource("applicationContext.xml")
public class ExampleApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(ExampleApplication.class, args);
    }

}

0
投票

注释不必(在类上)(具有主方法)(具有以下调用):

SpringApplication.run(Application.class,args);

(在你的情况下,我所说的是@ImportResource不必在你的班上)

公共类ExampleApplication {}

.........

你可以有一个不同的班级

@Configuration
@ImportResource({"classpath*:applicationContext.xml"})
public class XmlConfiguration {
}

或者为了清楚起见

@Configuration
@ImportResource({"classpath*:applicationContext.xml"})
public class MyWhateverClassToProveTheImportResourceAnnotationCanBeElsewhere {
}

本文中提到了上述内容

http://www.springboottutorial.com/spring-boot-java-xml-context-configuration

.........

奖金:

以防万一你可能认为“SpringApplication.run”是一种无效的方法......事实并非如此。

你也可以这样做:

public static void main(String[] args) {

        org.springframework.context.ConfigurableApplicationContext applicationContext = SpringApplication.run(ExampleApplication.class, args);

        String[] beanNames = applicationContext.getBeanDefinitionNames();
        Arrays.sort(beanNames);

        for (String name : beanNames) {
            System.out.println(name);
        }

这也会巧妙地提醒你所有的很多很多很多人(我提到“很多”?)....春天启动带来的依赖性。根据你说话的人,这是件好事(别人)为我做了所有的好事)或者是一件邪恶的事(哇,那是我无法控制的很多依赖)。

#标签:sometimesLookBehindTheCurtain


-1
投票

谢谢安迪,这使它非常简洁。但是,我的主要问题是将applicationContext.xml放入类路径中。

显然,将文件放入src/main/resources需要将它们放入类路径(通过将它们放入jar中)。我试图设置CLASSPATH,它被忽略了。在上面的例子中,负载似乎无声地失败。使用@ImportResource导致它冗长地失败(这帮助我追踪真正的原因)。

© www.soinside.com 2019 - 2024. All rights reserved.