如何开始?
访问Spring Initializer创建一个Spring项目,可以自己添加依赖等,然后可以在这个网站简单的下载一个项目结构的压缩包。
做一个web项目
第一步 创建一个Controller
Controller的作用是起到一个调度作用,用于接收浏览器端的访问请求。一个Controller文件的内容如下:
package com.example.springboot;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController {
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
使用@RestController
注解的类表示这是一个用于接收web访问的类。@RestController
是融合了@Controller
和 @ResponseBody
两个注解,作用是返回数据而不是View。
第二步 创建一个应用类(启动类)
package com.example.springboot;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
@SpringBootApplication
这个注解包含了以下几样注解的内容
@Configuration
将类标记为应用程序上下文的Bean定义的源。@EnableAutoConfiguration
命令Spring根据classpath中的设定自动加载bean@ComponentScan
命令Spring在com/example 这个目录下面自动扫描别的Components,Configurations 和 Services,寻找别的Controller
main()方法作为入口方法,当中的SpringApplication.run()方法用来启动spring应用。
这里官网demo中提供的一个commandLineRunner()方法,用来在应用启动开始的时候运行,打印一下运行的时候加载了那些bean。
试运行一下
在浏览器中输入:http://localhost:8080/
可以看到:Greetings from Spring Boot!
然后看一下在启动过程中加载了哪些beans:
application
applicationAvailability
applicationTaskExecutor
basicErrorController
beanNameHandlerMapping
beanNameViewResolver
characterEncodingFilter
commandLineRunner
conventionErrorViewResolver
defaultServletHandlerMapping
defaultViewResolver
dispatcherServlet
dispatcherServletRegistration
error
errorAttributes
errorPageCustomizer
errorPageRegistrarBeanPostProcessor
formContentFilter
handlerExceptionResolver
handlerFunctionAdapter
helloController
httpRequestHandlerAdapter
jacksonObjectMapper
jacksonObjectMapperBuilder
jsonComponentModule
lifecycleProcessor
localeCharsetMappingsCustomizer
mappingJackson2HttpMessageConverter
messageConverters
multipartConfigElement
multipartResolver
mvcContentNegotiationManager
mvcConversionService
mvcHandlerMappingIntrospector
mvcPathMatcher
mvcResourceUrlProvider
mvcUriComponentsContributor
mvcUrlPathHelper
mvcValidator
mvcViewResolver
org.springframework.aop.config.internalAutoProxyCreator
org.springframework.boot.autoconfigure.AutoConfigurationPackages
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
org.springframework.boot.autoconfigure