Loading applicationcontext.xml when using SpringApplication

最后都变了- 提交于 2019-12-05 03:30:12

If you'd like to use file from your classpath, you can always do this:

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

Notice the classpath string in @ImportResource annotation.

You can use @ImportResource to import an XML configuration file into your Spring Boot application. For example:

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

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

}

The annotation does not have to be (on the class) that (has the main method) that (has this below call):

SpringApplication.run(Application.class, args);

(in your case, what I am saying is that @ImportResource does NOT have to be on your class)

public class ExampleApplication {}

.........

You can have a different class

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

or for clarity

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

The above is mentioned in this article

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

.........

BONUS:

And just in case you may have thought "SpringApplication.run" was a void method.....that is NOT the case.

You can also do this:

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);
        }

This will also subtly clue you in to all the many, many, many (did I mention "many"?)....dependencies that spring boot is bringing in. Depending to whom you speak, this is a good thing (somebody else did all the nice figuring out for me) or an evil thing (whoah, that's a lot of dependencies that I don't control).

hashtag:sometimesLookBehindTheCurtain

Thanks Andy, that made it very concise. However, my main problem turned out to be getting applicationContext.xml into the classpath.

Apparently, putting files into src/main/resources is required to get them into the classpath (by placing them into the jar). I was attempting to set CLASSPATH which was just ignored. In my example above, the load seemed to fail silently. Using @ImportResource caused it to fail verbosely (which helped me track down the real cause).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!