构建项目

1.SpringBoot基础配置 - 图1
1.SpringBoot基础配置 - 图2

启动项目

  1. @RestController
  2. @SpringBootApplication
  3. public class DesignPatternApplication {
  4. @RequestMapping("/")
  5. @ResponseBody
  6. public String index() {
  7. return "Hello SpringBoot!!!";
  8. }
  9. public static void main(String[] args) {
  10. SpringApplication.run(DesignPatternApplication.class, args);
  11. }
  12. }
  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Inherited
  5. @SpringBootConfiguration
  6. @EnableAutoConfiguration
  7. @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  8. @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
  9. public @interface SpringBootApplication {
  10. }
  • @SpringBootConfiguration 注解,它继承自 @Configuration 注解,功能也跟 @Configuration 一样。它会将当前类标注为配置类了,我们在启动类中配置 Bean 就可以生效了。
  • @ComponentScan 注解,用来指定我们要扫描的包,以便发现 Bean 。注意在默认情况下, SpringBoot 扫描该注解标注类所在包及其子包。当我们的控制器、服务类等 Bean 放到不同的包中时,就需要通过 @ComponentScan 注解指定这些包,以便发现 Bean 。
  • @EnableAutoConfiguration 注解,用来启动自动配置。开启自动配置后, Spring Boot 会扫描项目中所有的配置类,然后根据配置信息启动 Spring 容器。

定制Banner

在src/main/resources目录下新建banner.txt文件,然后将自己的图案黏贴进去即可

ASCII图案可通过网站http://www.network-science.de/ascii/一键生成

  1. //关闭banner
  2. public static void main(String[] args) {
  3. SpringApplication app = new SpringApplication(DemoApplication.class);
  4. app.setBannerMode(Mode.OFF);
  5. app.run(args);
  6. }

全局配置文件

在src/main/resources目录下,Spring Boot提供了一个名为application.properties的全局配置文件,可对一些默认配置的配置值进行修改。

application.properties中可配置所有官方属性

自定义配置

  1. my.cat.name=mimi
  2. my.cat.age=3
  1. @Component
  2. @Data
  3. public class MyCat {
  4. @Value("${my.cat.name}")
  5. private String name;
  6. @Value("${my.cat.age}")
  7. private int age;
  8. }
  1. @Controller
  2. public class TestController {
  3. @Autowired
  4. private MyCat myCat;
  5. @RequestMapping(value = "/cat", produces = MediaType.APPLICATION_JSON_VALUE)
  6. @ResponseBody
  7. public MyCat getCat() {
  8. return myCat;
  9. }
  10. }

启动项目测试

多个配置文件处理

属性非常多的情况下,也可以定义一个和配置文件对应的Bean:通过注解 @ConfigurationProperties(prefix = “my.cat”) 指明了属性的通用前缀,通用前缀加属性名和配置文件的属性名一一对应。

  1. @Data
  2. @ConfigurationProperties(prefix = "my.cat")
  3. public class ConfigBean {
  4. private String name;
  5. private int age;
  6. }

还需在Spring Boot入口类加上注解@EnableConfigurationProperties({ConfigBean.class})来启用该配置:

  1. @SpringBootApplication
  2. @EnableConfigurationProperties({ ConfigBean.class })
  3. public class DesignPatternApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(DesignPatternApplication.class, args);
  6. }
  7. }
  1. @Autowired
  2. private ConfigBean configBean;
  3. @RequestMapping("/config")
  4. @ResponseBody
  5. public String index() {
  6. return configBean.getName()+"——"+configBean.getAge();
  7. }

属性之间可以相互引用

  1. my.cat.name=mimi
  2. my.cat.age=3
  3. my.cat.des=${my.cat.name} -- ${my.cat.age}

自定义配置文件

除了可以在application.properties里配置属性,我们还可以自定义一个配置文件。在src/main/resources目录下新建一个test.properties:

test.name=KangKang
test.age=25
@Configuration
@ConfigurationProperties(prefix="test")
@PropertySource("classpath:test.properties")
@Component
public class TestConfigBean {
    private String name;
    private int age;
    // get,set略
}

注解@PropertySource("classpath:test.properties")指明了使用哪个配置文件。要使用该配置Bean,同样也需要在入口类里使用注解@EnableConfigurationProperties({TestConfigBean.class})来启用该配置。

使用xml配置

虽然Spring Boot并不推荐我们继续使用xml配置,但如果出现不得不使用xml配置的情况,Spring Boot允许我们在入口类里通过注解@ImportResource({"classpath:some-application.xml"})来引入xml配置文件。

Profile配置

配置-springBoot

多环境配置文件必须以application-{profile}.properties的格式命,
application-dev.properties:

server.port=8080

application-pro.properties:

server.port=8081

需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。也可以在运行jar文件的时候使用命令java -jar xxx.jar --spring.profiles.active={profile}切换不同的环境配置。

spring.profiles.active=dev

配置-maven

集成模板引擎

theamleaf

引入pmo

<!-- 引入web项目相关依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- ThymeLeaf依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

创建控制器方法

@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @RequestMapping("/getAll")
    public String getUsers(Model model) {
        model.addAttribute("users", userService.getAllUser());
        return "user.html";
    }
}

创建html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>USERS</title>
</head>
<body>
    <div>用户列表</div>
    <div th:each="item:${users}">
        <span th:text="${item.name}"></span>
        <span th:text="${item.age}"></span>
        <span th:text="${item.address}"></span>
    </div>

</body>
</html>

启动项目,访问:http://localhost:8081/user/getAll

JSP

需要引入 Web 项目及 JSP 模板相关的依赖项
image.png

        <!-- 添加web开发功能 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--内嵌的tomcat支持模块 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- 对jstl的支持 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

添加视图解析器

@SpringBootApplication
public class SpringBootJspApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootJspApplication.class, args);
    }
    @Bean // 注册视图解析器
    public InternalResourceViewResolver setupViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");// 自动添加前缀
        resolver.setSuffix(".jsp");// 自动添加后缀
        return resolver;
    }
}