一、项目结构介绍

如上图所示,Spring Boot的基础结构共三个文件:

src/main/java  程序开发以及主程序入口

src/main/resources 配置文件

src/test/java  测试程序

二、application.properties 配置文件

默认启动项目的url配置,不需要加项目路径默认为/ 可以自行修改。

端口默认8080 修改端口号为8888

项目名称server.context-path

server.port=8888
server.context-path=/HelloWorld

helloWorld=spring boot
@Value("${helloWorld}")根据key-value直接注入helloWorld

@RestController
public class HelloWorldController {

@Value("${helloWorld}")
private String helloWorld;

@RequestMapping("/helloWorld")
public String say(){
return helloWorld;
}

}
@RestController的意思就是controller里面的方法都以json格式输出,不用再写什么jackjson配置的了!

启动主程序,打开浏览器访问http://localhost:8080/HelloWorld/helloWorld,就可以看到效果了。页面输出spring boot

三、@Value将外部配置文件的值动态注入到Bean

配置文件主要有两类:

application.properties。application.properties在spring boot启动时默认加载此文件
自定义属性文件。自定义属性文件通过@PropertySource加载。@PropertySource可以同时加载多个文件,也可以加载单个文件。如果相同第一个属性文件和第二属性文件存在相同key,则最后一个属性文件里的key启作用。加载文件的路径也可以配置变量,如下文的${anotherfile.configinject},此值定义在第一个属性文件config.properties
第一个属性文件config.properties内容如下: 
${anotherfile.configinject}作为第二个属性文件加载路径的变量值

book.name=bookName
anotherfile.configinject=placeholder
第二个属性文件config_placeholder.properties内容如下:

book.name.placeholder=bookNamePlaceholder
下面通过@Value(“${app.name}”)语法将属性文件的值注入bean属性值

@Component
// 引入外部配置文件组:${app.configinject}的值来自config.properties。
// 如果相同
@PropertySource({"classpath:com/hry/spring/configinject/config.properties",
"classpath:com/hry/spring/configinject/config_${anotherfile.configinject}.properties"})
public class ConfigurationFileInject{
@Value("${app.name}")
private String appName; // 这里的值来自application.properties,spring boot启动时默认加载此文件

@Value("${book.name}")
private String bookName; // 注入第一个配置外部文件属性

@Value("${book.name.placeholder}")
private String bookNamePlaceholder; // 注入第二个配置外部文件属性

@Autowired
private Environment env; // 注入环境变量对象,存储注入的属性值

public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("bookName=").append(bookName).append("\r\n")
.append("bookNamePlaceholder=").append(bookNamePlaceholder).append("\r\n")
.append("appName=").append(appName).append("\r\n")
.append("env=").append(env).append("\r\n")
// 从eniroment中获取属性值
.append("env=").append(env.getProperty("book.name.placeholder")).append("\r\n");
return sb.toString();
}
}
Application.java同上文

@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
public class ConfiginjectApplicationTest {
@Autowired
private ConfigurationFileInject configurationFileInject;

@Test
public void configurationFileInject(){
System.out.println(configurationFileInject.toString());
}
}
测试结果

bookName=bookName
bookNamePlaceholder=bookNamePlaceholder
appName=appName
env=StandardEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[Inlined Test Properties,systemProperties,systemEnvironment,random,applicationConfig: [classpath:/application.properties],class path resource [com/hry/spring/configinject/config_placeholder.properties],class path resource [com/hry/spring/configinject/config.properties]]}
env=bookNamePlaceholder
四、application.properties配置数据库连接

有前缀的属性注入

请求url

mysql.jdbcName=com.mysql.jdbc.Driver
mysql.dbUrl=jdbc:mysql://localhost:3306/db_boot
mysql.userName=root
mysql.password=123456
@Component 让spring加载

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
* Mysql属性配置文件
* @author Administrator
*
*/
@RestController
public class MysqlProperties {
@Value("${mysql.jdbcName}")
private String jdbcName;
@Value("${mysql.dbUrl}")
private String dbUrl;
@Value("${mysql.userName}")
private String userName;
@Value("${mysql.password}")
private String password;

public String getJdbcName() {
return jdbcName;
}

public void setJdbcName(String jdbcName) {
this.jdbcName = jdbcName;
}

public String getDbUrl() {
return dbUrl;
}

public void setDbUrl(String dbUrl) {
this.dbUrl = dbUrl;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}
@ConfigurationProperties(prefix="mysql") 就是application配置文件的前缀mysql

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
* Mysql属性配置文件
* @author Administrator
*
*/
@Component
@ConfigurationProperties(prefix="mysql")
public class MysqlProperties {

private String jdbcName;

private String dbUrl;

private String userName;

private String password;

public String getJdbcName() {
return jdbcName;
}

public void setJdbcName(String jdbcName) {
this.jdbcName = jdbcName;
}

public String getDbUrl() {
return dbUrl;
}

public void setDbUrl(String dbUrl) {
this.dbUrl = dbUrl;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}
@Component已经变为spring管理的bean了@Resource  直接引入

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

@Resource
private MysqlProperties mysqlProperties;

@RequestMapping("/showJdbc")
public String showJdbc(){
return "mysql.jdbcName:"+mysqlProperties.getJdbcName()+"<br/>"
+"mysql.dbUrl:"+mysqlProperties.getDbUrl()+"<br/>"
+"mysql.userName:"+mysqlProperties.getUserName()+"<br/>"
+"mysql.password:"+mysqlProperties.getPassword()+"<br/>";
}
}
五、spring处理http请求

@Controller 处理http请求的注解,请求后台转发页面

@RequestMapping 映射路径

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/freemarker")
public class HelloWorldFreemarkerController {

@RequestMapping("/say")
public ModelAndView say(){
ModelAndView mav=new ModelAndView();
mav.addObject("message", "springboot!");
mav.setViewName("helloWorld");
return mav;
}
}
helloWorld的模板文件

helloWorld.ftl

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
show: ${message}
</body>
</html>
@PathVariable获取url参数

@RequestParam 获取get或post参数或者是form和url参数

rest风格的资源url请求

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://www.java1234.com/jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript">
function show(){
$.post("ajax/hello",{},function(result){
alert(result);
});
}

</script>
</head>
<body>
<button οnclick="show()">你好</button>
<a href="/HelloWorld/blog/21">天天</a>
<a href="/HelloWorld/blog/query?q=123456">搜索</a>
</body>
</html>
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ajax")
public class HelloWorldAjaxController {

@RequestMapping("/hello")
public String say(){
return "{'message1':'SpringBoot你好','message2','Spring你好2'}";
}
}
@PathVariable获取url参数

<a href="/HelloWorld/blog/21"></a>
<a href="/HelloWorld/blog/query?q=123456">搜索</a>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/blog")
public class BlogController {

@RequestMapping("/{id}")
public ModelAndView show(@PathVariable("id") Integer id){
ModelAndView mav=new ModelAndView();
mav.addObject("id", id);
mav.setViewName("blog");
return mav;
}

@RequestMapping("/query")
public ModelAndView query(@RequestParam(value="q",required=false)String q){
ModelAndView mav=new ModelAndView();
mav.addObject("q", q);
mav.setViewName("query");
return mav;
}
}
blog.ftl

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
id:${id}
</body>
</html>
---------------------
作者:wespten
来源:CSDN
原文:https://blog.csdn.net/qq_35029061/article/details/81926967
版权声明:本文为博主原创文章,转载请附上博文链接!

转载于:https://www.cnblogs.com/telwanggs/p/10779884.html

Spring 的application.properties项目配置与注解相关推荐

  1. Spring Boot application.properties 常用配置

    SPRING CONFIG (ConfigFileApplicationListener) spring.config.name 配置文件名称,默认为application spring.config ...

  2. spring cloud ,spring boot application.properties 配置属性列表

    #横幅 banner.charset = UTF-8#横幅文件编码. banner.location = classpath:banner.txt#横幅文件位置. banner.image.locat ...

  3. Spring Boot 菜鸟教程 application.properties 常用配置

    SPRING CONFIG (ConfigFileApplicationListener) spring.config.name 配置文件名称,默认为application spring.config ...

  4. application.properties文件配置详解(核心属性和Web属性) ——Spring Boot配置

    ****************************************核心属性配置***************************************** # 文件编码 banne ...

  5. spring boot application.properties 属性详解

    2019年3月21日17:09:59 英文原版: https://docs.spring.io/spring-boot/docs/current/reference/html/common-appli ...

  6. springboot2的application.properties 官方配置 说明文件(中文翻译)

    #================================================= ==================  #COMMON SPRING BOOT PROPERTIE ...

  7. spring配置文件application.properties配置项及含义

    server.servlet.context-path 和 server.context-path :配置项目的上下文路径.以"/"开始.如果已经配置上下文路径,则访问时需要加入路 ...

  8. springboot中配置文件application.properties的配置详情,数据源配置

    pring Boot使用了一个全局的配置文件application.properties,放在src/main/resources目录下或者类路径的/config下.Sping Boot的全局配置文件 ...

  9. 关于Spring中的context:annotation-config/配置(开启注解)

    转自:https://www.cnblogs.com/doudouxiaoye/p/5681518.html 当我们需要使用BeanPostProcessor时,直接在Spring配置文件中定义这些B ...

最新文章

  1. 2021年春季学期-信号与系统-第八次作业参考答案-第六小题
  2. 通过form表单请求servlet资源代码
  3. SpringMVC的Controller方法返回值
  4. arduino python firmate_processing firmata协议及数组训练
  5. Docker for windows 10
  6. Django从理论到实战(part51)--User模型
  7. 老师“鬼话”全曝光!哈哈哈哈哈全国的老师都这样吗?
  8. npm使用国内镜像加速的几种方法
  9. Excel develop
  10. 从0到1分步实现一个出生日期的正则表达式(JavaScript)
  11. 全新液体镜头专利曝光:华为P50系列拍照对焦速度堪比人眼
  12. oracle基础入门(二)
  13. android handler的机制和原理_第一百八十回:Android中的Handler机制九
  14. JVM飙高排查脚本-结构分析
  15. mysql中kill掉所有锁表的进程
  16. Windows域控统一设置客户端桌面壁纸【全域策略生效】
  17. keil中下载按钮和调试按钮灰掉了
  18. SAP那些事-理论篇-7-SAP的优势和劣势
  19. mac lnmp 安装mysql_Mac安装LNMP环境
  20. 携程酒店价格关键信息记录

热门文章

  1. c语言存储类型重要吗,C语言储存类别(Storage Class)
  2. SkyEye图形化界面使用技巧篇(二)
  3. elasticsearch获取一个字段的值_Elasticsearch,你觉得自己懂了多少,看看这篇文章吧...
  4. (07)FPGA基本组成单元
  5. (43)Verilog HDL 二分频设计
  6. eve服务器维护后怪物刷新,【独家披露】EVE异常空间怪物那些事儿(一)普通异常...
  7. 机械硬盘4k读写速度_三星T5移动硬盘应用评测:不止够用,还很好用
  8. 链表在STM32中的应用
  9. 如何让程序一直运行_VBA程序正式运行前,要该如何进行调试呢?
  10. Linux驱动之设备模型(1)