微服务微服务架构和实践

SpringBoot开发深入

2018-03-18  本文已影响53人  Coding小聪

设置环境属性

SpringBoot默认启动的端口是8080,如果要换成别的端口就需要设置端口属性覆盖默认值,我们需要通过在项目中的"src/main/resources"下创建application.properties文件(或者是application.yml文件)。

YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)。和properties文件简单区别,如properties文件中db.username=root,转换成yml的格式则为
db:
username: root
具体格式请参考:YAML 语言教程

如果要改变端口,则在applicaiton.xml文件中配置server.port即可

server.port=80
# 配置contextPath,访问路径变为: http://127.0.0.1/springboot/xxx
server.context-path=/springboot

如果是使用application.yml文件,配置如下

server:
  port: 80
  context-path: /springboot

读取资源文件

实际开发中我们常需要读取资源文件,国际化也需要依赖资源文件。下面分步骤讲解一下在springboot中如何读取资源文件。

  1. 在src/main/resources目录下建立i18n文件夹;
  2. 在i18n目录中创建2个资源文件
    Messages.properties文件
welcome.url=www.google.com
welcome.msg=\u6b22\u8fce{0}\u5149\u4e34\uff01

Pages.properties文件

member.add.page=/pages/back/admin/member/member_add.jsp
member.add.action=/pages/back/admin/member/member_add.action
  1. 在applicaion.yml文件中增加如下配置
spring:
  messages:
    basename: i18n/Messages,i18n/Pages
  1. 创建读取配置信息的控制器类MessageController
@RestController
public class MessageController {
    @Resource
    private MessageSource messageSource; // 自动注入此资源对象

    @RequestMapping(value = "showMsg",method = RequestMethod.GET)
    public String showMessage(String user){
        System.out.println("request url:" + this.getMessage("member.add.action"));
        return this.getMessage("welcome.msg", user);
    }

    private String getMessage(String key,String... args) {
        return messageSource.getMessage(key,args, Locale.getDefault());
    }
}

配置Bean

SpringBoot没有单独提供配置Bean的方式,它配置Bean的方式还是得依赖Spring提供的方式。Spring中提供了3中装配Bean的方式

自动化配置bean

自动配置一般使用的最多,通过@Controller、@Service、@Component等注解完成Bean的配置,而通过@Resource、@Autowired注解完成依赖的注入。不过默认情况下自动配置不是开启的,在传统Spring项目中可以通过在Java配置类中增加@ComponentScan注解或者在xml配置文件中加入<context:component-scan base-package="cn.zgc"/>配置来打开组件扫描功能。在Springboot中,通过在启动类中加入@SpringBootApplication注解既能打开组件扫描功能,默认扫描路径为启动类所在的包路径。

Java配置文件类配置bean

package cn.zgc.springboot.advanced.config;

import cn.zgc.springboot.advanced.service.impl.MessageJavaConfigServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration  // 此处为配置项
public class ServiceConfig {
    @Bean(name="configService")     // 此处返回的是一个Spring的配置Bean,与xml的“<bean>”等价
    public MessageJavaConfigServiceImpl getMessageService() {
        return new MessageJavaConfigServiceImpl() ;
    }
}

XML文件配置bean

一般情况下,是不推荐使用xml文件进行配置的,但是如果非要在Springboot项目中使用xml文件该如何办呢?可以在程序启动类上使用 @ImportResource注解引入xml 文件进行配置加载

@SpringBootApplication // 启动SpringBoot程序,而后自带子包扫描
@ImportResource(locations={"classpath:spring-common.xml"})
public class StartSpringBootMain {
 public static void main(String[] args) throws Exception {
 SpringApplication.run(StartSpringBootMain.class, args);
 }
}

profile配置

实际项目中一般会存在多个环境,例如:开发、测试、生产。每个环境都有自己不同的配置,我们可以借助spring的profile来方便的实现不同环境之间的切换。profile的配置针对项目中使用的是application.yml还是application.properties有所不同,下面讲解是基于application.yml的。

  1. 在application.yml文件中配置如下内容
spring:
  profiles:
    active: product
---
spring:
  messages:
    basename: i18n/Messages,i18n/Pages
  profiles: dev
server:
  port: 8080
---
spring:
  messages:
    basename: i18n/Messages,i18n/Pages
  profiles: test
server:
  port: 9090
---
spring:
  messages:
    basename: i18n/Messages,i18n/Pages
  profiles: product

可以看到不同环境所启动的端口有所不同。

  1. 对工程进行打包,然后进行不同环境的切换。
    打包命令:clean package
    切换不同环境指令:java -jar microboot.jar --spring.profiles.active=test 如果直接运行java -jar xxx.jar则运行的是yml文件中配置的激活(active,示例中为product)的环境

  2. 打包的时候,页面和一些资源文件也需要一起打到jar包中,这时需要在pom文件中加入以下配置

<resources>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.yml</include>
            <include>**/*.xml</include>
            <include>**/*.tld</include>
        </includes>
        <filtering>false</filtering>
    </resource>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
            <include>**/*.tld</include>
        </includes>
        <filtering>false</filtering>
    </resource>
    <resource>
        <directory>src/main/view</directory>
        <includes>
            <include>**/*.*</include>
        </includes>
        <filtering>false</filtering>
    </resource>
</resources>

页面模板渲染

常见的页面模板渲染技术有:FreeMarker、Velocity、Thymeleaf,Spring官方推荐使用Thymeleaf。下面介绍一下如何在springboot中使用Thymeleaf。

  1. 在pom文件中导入thymeleaf的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 创建controller类,通过Model向显示层传递参数
@Controller
public class ThymeleafController {
    @RequestMapping(value = "/thymeleaf", method = RequestMethod.GET)
    public String toThymeleaf(String username, Model model){
        model.addAttribute("username",username);
        model.addAttribute("password","123456789");
        // 此处返回的是一个路径, 该路径的后缀默认是*.html
        return "message/user";
    }
}
  1. 创建页面文件,thymeleaf相关的页面文件保存的路径是有规定的:在CLASSPATH路径下(src/main/resources、src/main/view)必须建立有一个templates的目录,在这个目录里面保存有thymeleaf的页面,这些页面可以按照文件目录保存。
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>SpringBoot模版渲染</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
    <p th:text="'用户名:' + ${username}"/>
    <p th:text="'密码:' + ${password}"/>
</body>
</html>
<!-- 注意该文件中所有的标签都要正常结束 -->
  1. 如果现在我们所定义的要访问的页面不是通过控制器跳转的怎么办?那么为了解决这样的问题,可以考虑在 thymeleaf 所在的父路径中“src/main/view”建立一个 static 的子目录,该目录保存的是所有静态页面。项目中的静态的资源都放入该目录下。 springboot页面资源路径

    如果要更改thymeleaf页面默认的后缀,可以在application.yml文件中加入如下配置(页面文件的后缀要和修改后的后缀保持一致)

spring: 
 thymeleaf:
 suffix: .htm
上一篇下一篇

猜你喜欢

热点阅读