资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

GenericApplicationContext怎么在SpringBoot中使用

今天就跟大家聊聊有关GenericApplicationContext怎么在Spring Boot中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

创新新互联,凭借十载的成都网站制作、做网站经验,本着真心·诚心服务的企业理念服务于成都中小企业设计网站有数千家案例。做网站建设,选成都创新互联

Spring Boot的POM.xml:



  4.0.0

  com.zetcode
  genappctx
  0.0.1-SNAPSHOT
  jar

  genappctx
  Using GenericApplicationContext

  
    org.springframework.boot
    spring-boot-starter-parent
    2.1.0.RELEASE
     
  

  
    UTF-8
    UTF-8
    11
  

  
    
      org.springframework.boot
      spring-boot-starter
    

    
      org.springframework.boot
      spring-boot-starter-test
      test
    
  

  
    
      
        org.springframework.boot
        spring-boot-maven-plugin
      
    
  

这是Maven pom.xml文件。这spring-boot-starter-parent是一个父POM,为使用Maven构建的应用程序提供依赖性和插件管理。它spring-boot-starter是核心启动器,包括自动配置支持,日志记录和YAML。在spring-boot-starter-test春季增加了测试支持。将spring-boot-maven-pluginSpring应用程序包转换为可执行的JAR或WAR归档文件。

application.properties:

spring.main.banner-mode = off 
logging.level.root = ERROR 
logging.pattern.console =%d {dd-MM-yyyy HH:mm:ss}%magenta([%thread])%highlight(% - 5level) )%logger。%M - %msg%n

这个application.properties是Spring Boot中的主要配置文件。我们关闭Spring标题,仅减少记录到错误的数量,并设置控制台日志记录模式。

TimeService.java:

public class TimeService {

  public Instant getNow() {

    return Instant.now();
  }
}

TimeService包含一个返回当前日期和时间的简单方法。此服务类将在我们的通用应用程序上下文中注册。

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

  @Autowired
  private GenericApplicationContext context;

  public static void main(String[] args) {

    SpringApplication.run(MyApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {

    context.registerBean("com.zetcode.Service.TimeService",
        TimeService.class, () -> new TimeService());

    var timeService = (TimeService) context.getBean(TimeService.class);

    System.out.println(timeService.getNow());

    context.registerShutdownHook();
  }
}

MyApplication是设置Spring Boot应用程序的入口点。该@SpringBootApplication注释能够自动配置和组件扫描。这是一个方便的注释,等同于@Configuration,@EnableAutoConfiguration以及@ComponentScan注释。

这里我们注入了GenericApplicationContext。使用该registerBean()方法注册了 一个新的TimeService bean 。

下面是测试MyApplicationTests.java:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyApplicationTests {

  @Autowired
  private GenericApplicationContext context;

  @Test
  public void testNow() {

    var timeService = (TimeService) context.getBean("com.zetcode.Service.TimeService");
    var now = timeService.getNow();

    assertThat(now.isBefore(Instant.now()));
  }
}

运行:

mvn -q spring-boot:run

看完上述内容,你们对GenericApplicationContext怎么在Spring Boot中使用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


网页题目:GenericApplicationContext怎么在SpringBoot中使用
分享URL:http://cdkjz.cn/article/igpgjd.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220