SpringBoot(二):设置springboot同一接口程序启动入口

根据上一篇文章中搭建了一个springboot简单工程,在该工程中编写HelloWordController.java接口类,并在该类中写了一个main函数,做为该类的接口服务启动入口。此时如果新增多个接口服务类时,不修改任何代码是无法访问新增类的接口服务。

实际上springboot提供了统一配置全局扫描接口服务类的启动方法,本文就介绍如何使用:

如何配置统一启动入口

在src根目录下新建一个app包,在包下创建一个App.java类,通过代码配置使其作为该工程的一个通用启动入口类:

package app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan("com.dx.controller")
@EnableAutoConfiguration
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

备注:

1)ComponentScan用来配置目前扫描类所在包的路径;

2)EnableAutoConfiguration自动注入;

3)SpringApplication.run(App.class,args)用来作为服务器启动入口,目的启动接口服务。

测试接口服务类:

已经拥有的接口服务类有:

HelloWordController.java

package com.dx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloWordController {
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        System.out.println("index is running...");
        return "welcome";
    }
}

RestControllerTest.java

package com.dx.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class RestControllerTest {
    @RequestMapping("/rest")
    public Map<String, Object> rest() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", "404");
        result.put("msg", "unkown");

        return result;
    }

}

,运行app.App.java类,等待启动完成后。

1)访问:http://127.0.0.1:8888/rest

2)访问:

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值