SpringBoot 02: 初识SpringBoot( 二 )

【SpringBoot 02: 初识SpringBoot】@Component@ConfigurationProperties(prefix = "school")public class SchoolInfo {private String name;private String website;private String address;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getWebsite() {return website;}public void setWebsite(String website) {this.website = website;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "SchoolInfo{" +"name='" + name + '\'' +", website='" + website + '\'' +", address='" + address + '\'' +'}';}}使用jsp

  • SpringBoot不推荐使用jsp, 而是使用模板技术代替jsp
  • 如果要使用jsp, 需要添加如下依赖,负责编译jsp文件
<dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId></dependency>
  • 如果需要使用servlet, jsp, jstl的功能, 需要添加如下依赖
<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId></dependency><dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId></dependency><dependency><groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version></dependency>
  • 创建一个存放jsp的目录, 一般为src/main/webapp目录,记得设置webapp的目录属性
  • 需要在pom.xml指定jsp文件编译后的存放目录:META-INF/resources
<resource> <directory>src/main/webapp</directory> <targetPath>META-INF/resources</targetPath> <includes><include>**/*.*</include> </includes></resource>
  • 创建Controller, 访问jsp
  • 在application.propertis文件中配置视图解析器
#配置视图解析器spring.mvc.view.prefix=/spring.mvc.view.suffix=.jsp手动使用SpringBoot容器获取对象
  • 关注SpringBoot工程的主启动类的run方法
@SpringBootApplicationpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
  • 关注上述run方法的返回值
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {return run(new Class[]{primarySource}, args);}
  • 而ConfigurableApplicationContext是ApplicationContext的子接口
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {}
  • 所以接收SpringBoot主启动类的run方法的返回值就可以获取到SpringBoot容器
  • 之后便可以按照需求调用SpringBoot容器的方法获取已经注册到容器中的对象
CommandLineRunner接口 与 ApplcationRunner接口
  • 两个接口
@FunctionalInterfacepublic interface CommandLineRunner {void run(String... args) throws Exception;}@FunctionalInterfacepublic interface ApplicationRunner {void run(ApplicationArguments args) throws Exception;}
  • 两个接口都有一个run方法
  • SpringBoot项目的主启动类实现上述接口,重写run方法,在容器对象创建好后自动执行run()方法
  • 可以在容器对象创建好后完成一些自定义的操作

推荐阅读