该文章为了记录自己看官方文档做出官方demo(示例),以及记录@GetMapping注释引用hello方法的稍微改动。
本人的实验环境:Windows10----IDEA----java8
首先,官方要求我们去:官方的配置打包网站
进行打包并且下载好文档,下图是我的配置选择,这里进行的是一个spring boot基本项目,需要的依赖是spring web
然后点击最下方的菜单栏里面的这个:
等待它下载完成,并解压它,然后用IDEA导入:
最后点击确认就可以导入进IDEA了,导入之后长这样子:
代码:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
在这里插入一下各个注释的意思:@SpringBootApplication是启动spring boot的关键,一般在主类的上方(这里主类是DemoApplication)、@RestController这个是标记DemoApplication作为一个控制器、@GetMapping("/hello")则是获取http的映射,起到路由的作用,让浏览器可以在/hello这个路由里返回hello方法的值。
到这里的话就已经完成了,点击绿色箭头运行:
运行成功:
在浏览器输入:http://localhost:8080/hello 就可以看到:
如果你在 http://localhost:8080/hello 后面加上 ?name=zhangsan 你会发现:
World 变成了zhangsan
以上就是官网的例子
然后我想着把hello方法给弄出来在IDEA里面直接赋值给name参数,我就这样做了:
添加了一点代码,并且改变了@GetMapping注释的位置:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
@GetMapping("/hello")
public String print(){
String a ;
a = hello("张三");
return a;
}
}
结果就可以在print方法里面用hello方法在IDEA里面直接赋值了
浏览器运行截图:
本人刚刚接触spring boot,如有不当之处敬请指出。