一、项目结构介绍

如上图所示,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 onclick="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
版权声明:本文为博主原创文章,转载请附上博文链接!

Spring 的application.properties项目配置与注解的更多相关文章

  1. spring boot application.properties基本配置

    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://loca ...

  2. 【转】spring boot application.properties 配置参数详情

    multipart multipart.enabled 开启上传支持(默认:true) multipart.file-size-threshold: 大于该值的文件会被写到磁盘上 multipart. ...

  3. Spring boot application.properties 配置

    原文链接: http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.ht ...

  4. Inspection info: Checks Spring Boot application .properties configuration files. Highlights unresolved and deprecated configuration keys and in

    Cannot resolve class or package ‘jdbc’ less… (Ctrl+F1) Inspection info: Checks Spring Boot applicati ...

  5. SpringBoot在logback.xml中读取application.properties中配置的日志路径

    1.在springboot项目中使用logback记录日志,在logback.xml中配置日志存储位置时读取application.properties中配置的路径,在 logback.xml中配置引 ...

  6. 使用 application.properties 中配置的属性,举例:@Value("${server.port}")

    使用 application.properties 中配置的属性:@Value 注解. @RestController public class HelloWorldController { @Val ...

  7. Spring boot 的application.properties 全局配置

    端口号.项目名称 application.properties: server.port=8888 server.context-path=/start 日志相关的配置 # 自定义日志配置路径 log ...

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

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

  9. spring boot application.properties 配置参数详情

    multipart multipart.enabled 开启上传支持(默认:true) multipart.file-size-threshold: 大于该值的文件会被写到磁盘上 multipart. ...

随机推荐

  1. 第一册:lesson7-8.

    原文:Are you a teacher? A:I am a  new student ,my name is A. B:Nice to meet you,my name is B. A:Are yo ...

  2. 写一个ORM框架的第一步(Apache Commons DbUtils)

    新一次的内部提升开始了,如果您想写一个框架从Apache Commons DbUtils开始学习是一种不错的选择,我们先学习应用这个小“框架”再把源代码理解,然后写一个属于自己的ORM框架不是梦. 一 ...

  3. Font Awesome 供更精准的图标搜索

    https://www.thinkcmf.com/font/font_awesome/icon/address-book

  4. 解决org.hibernate.HibernateException: identifier of an instance of com.ahd.entity.Order was altered from2 to 0

    错误信息 严重: Servlet.service() for servlet [springmvc] in context with path [/order] threw exception [Re ...

  5. Dom对象的研究

    1.逻辑运算  ||  &&  ! 1||2   5&&4     !0 || 遇到第一个为true 的数字就终止并返回 && 遇到第一个为false ...

  6. 关于 Socket 设置 setSoTimeout 误用的说明

    做网络开发的想必对setSoTimeout这个方法很熟悉,知道是设置的超时事件.但是很多人都认为这个是设置链路的超时时间,但是查看相关文档的此方法的说明: HttpConnectionParams: ...

  7. IO学习二(节点流)

    1.流的分类 按照数据流向的不同:输入流和输出流 按照处理数据的单位不同:字节流((非文本文件)视频.音频.图像).字符流(文本文件) 按照角色的不同:节点流和处理流 2.IO体系 抽象基类 节点流 ...

  8. Dynamics 365 Online-试用环境申请地址

    https://trials.dynamics.com/Dynamics365/Signup/sales 需要用企业邮箱

  9. 【linux】Can't connect to local MySQL server through socket和Plugin 'auth_socket' is not loaded报错

    真的是一次吐血的经历,弄了两个多小时才弄好. 问题1:直接登陆root用户报错 ERROR 2002 (HY000): Can't connect to local MySQL server thro ...

  10. 2014年11月17~11月18日,杨学明老师《企业IT需求收集和实施》内训在湖南长沙某酒店成功举办!

    2014年11月17至18日,受湖南某软件企业的邀请,杨学明老师<企业IT需求收集和实施>内训在某长沙某五星级酒店成功举办!来自全国各地的IT高管和企业负责人参加了此次培训.杨学明老师分别 ...