本文共 2681 字,大约阅读时间需要 8 分钟。
先记录几个小点:
查看idea中注解的源码用ctrl+鼠标左键 favicon.ico:(是因为浏览器会发送/favicon.ico请求获取到图标,整个session期间不再获取) 图标文件,复制一个图片之后放在静态资源目录下,运行后打开:下面解决问题:
今天创建idea里面spring initializr的maven工程,没有导其他的jar包,project modules:端口8080一开始被占用,然后输入命令:
taskkill /pid xxxx -f
netstat -ano | findstr 8080
然后8080端口可以启动了,但是一开始打开后虽然tomcat已经start了,但是页面并没有显示东西,反而一直是state 404(并不是无法连接的页面:)
而是: 但是我明明写了一个HelloController.java:package boot.controller;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@Slf4j//@ResponseBody 返回的这句话要以字符串的形式发给浏览器@RestControllerpublic class HelloController { @RequestMapping("/he") public String handle01() { log.info("请求.."); return "Hello,stirng"; }}
如果运行成功应该页面会显示字符串。
然后检查了之后发现好像包的位置不太对,myapplication在里面,HelloController.java在外面,然后修改了目录的包位置,现在位置如下: 把端口在application.properties改成了8081,banner也改了一下: Myconfig.java:package config;import boot.bean.Pet;import boot.bean.User;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;@Import({ User.class})@Configuration//用来告诉springboot这是一个配置类 等同于spring的配置文件public class Myconfig { // 外部无论对配置类中这个组件注册方法调用多少次获取的都是之前注册的容器中的单实例 @Bean//配置类中使用@Bean标注在方法上给容器注册组件,默认也是单实例的 ,给容器中注册组件 public User user01()//这是一个方法 可认为给容器中注册了一个user01组件 { return new User("zhangsan",19); } @Bean public Pet per() { return new Pet("tomcat"); }}
MyApplication.java:
package boot;import boot.bean.User;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.ConfigurableApplicationContext;/*这个注解是来表示这个是一个springboot应用 属于主程序类*/@SpringBootApplication //(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})public class MyApplication { public static void main(String[] args) { ConfigurableApplicationContext run = SpringApplication.run(MyApplication.class, args); String[] beanNamesfortype = run.getBeanNamesForType(User.class);for(String s: beanNamesfortype){ System.out.println(s);} }}
再次运行:
打开8081: 可以看到显示了字符串。以后要注意记得目录下各个包存放的文件位置。
新建Person.java类, 一开始只添加了标注@ConfigurationProperties,一直标红:在类上添加上注解@Component就好了:
springboot中指定访问静态资源路径前缀:
application.yml中加上:spring: mvc: static-path-pattern: /res/**
此时访问静态资源路径上要加上res:http://localhost:8081/res/me.jpg
(指定了端口8081) 但是访问请求时还是不能加前缀: http://localhost:8081/he 指定静态资源文件夹:resources: static-locations: classpath: /haha
static下新建html页面,后通过localhost也可以直接访问,即欢迎页:
转载地址:http://yvten.baihongyu.com/