如何在 Spring Boot 应用程序中使用 Spring

x33g5p2x  于2022-10-05 转载在 Spring  
字(1.0k)|赞(0)|评价(0)|浏览(712)

如果您有 Spring 应用程序,使用多个 XML 配置文件,您仍然可以将它们与 Spring Boot 集成。 让我们看看本教程中的方法。

导入 Spring 应用程序基本上需要导入它们的资源。 在下面的示例中,我们使用 @ImportResource 导入上下文文件。 :

  1. @ImportResource({
  2. "META-INF/spring/services-context.xml",
  3. "META-INF/spring/repositories- context.xml"
  4. })
  5. @SpringBootApplication
  6. public class SpringApplication {
  7. @Autowired TaskRepository task;
  8. @Autowired ServiceFacade service;
  9. //More logic...
  10. }

为了访问 bean,我们将它们自动连接到类成员。 这是另一个示例,它显示了如何重用类路径中的现有 XML 配置文件。

  1. @ImportResource("classpath:applicationContext.xml") @Configuration public class XMLConfiguration {
  2. @Autowired Connection connection;
  3. //Derived from the applicationContext.xml file.
  4. @Bean Database getDatabaseConnection() {
  5. return connection.getDBConnection();
  6. }
  7. }

以下代码显示了如何使用 ConfigurableApplicationContext 在现有 Java 配置类中重用 XML。 您还可以使用主类方法来获取现有的 XML 文件:

  1. public class Application {
  2. public static void main(String[] args) throws Exception {
  3. ConfigurableApplicationContext ctx =
  4. new SpringApplication("/META-INF/spring/integration.xml").run(args);
  5. System.out.println("Hit Enter to terminate");
  6. System.in.read();
  7. ctx.close();
  8. }
  9. }

相关文章