赞
踩
前言:在SpringBoot框架中,有两种文件配置,一种为application.properties,一种是application.yml,本篇文章主要以application.properties为例来验收对应的DEMO示例
在application.properties中添加参数
name=pxs
age=10
获取参数值的几种方式
通过ApplicationContext上下文获取 | 在Application类中,通过run方法的返回值获取ApplicationContext |
---|---|
通过@Value注解来获取 | 可以在Controller中使用,也可以在Bean中使用 |
通过@ConfigurationPorperties和@Component注解来获取 | 在Bean中使用 |
通过@ConfigurationPorperties和@Bean注解来获取 | 在Application中使用 |
(1)、ApplicationContext
ConfigurableApplicationContext app = SpringApplication.run(Application.class,args);
System.out.println(app.getEnvironment().getProperty("name"));
(2)、@Value
@Value("${name}")
private String name;
@Value("${age}")
private int age;
(3)、@ConfigurationPorperties和@Component
在application.properties中添加参数
test.name=pxs
test.age=10
@Component @ConfigurationProperties(prefix = "test") public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } }
(4)、@ConfigurationPorperties和@Bean
@SpringBootApplication
public class Application {
@Bean
@ConfigurationProperties(prefix = "test")
public User UserSettings(){
return new User();
}
public static void main(String args[]) {
SpringApplication.run(Application.class, args);
}
}
···使用@ConfigurationProperties(3 and 4)的实现
@Autowired
private Person person;
@RequestMapping("/getPerson")
public String getPerson() {
return person.toString();
}
下面是Spring Boot 连接数据库的参数设置:
spring.mvc.view.prefix=/WEB-INF/views/ spring.mvc.view.suffix=.jsp spring.thymeleaf.cache=false spring.thymeleaf.enabled=false spring.datasource.url=jdbc:mysql://localhost:3306/db_mysql?useSSL=false spring.datasource.username=root spring.datasource.password=mysql spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql= true
spring boot 默认使用的是thymeleaf 模板,所以如果想要使用springmvc模式的话就需要进行设置;
#与springmvc设置视图解析器类似
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
#如果想要使用springmvc,就需要取消掉原本默认的thymeleaf设置
spring.thymeleaf.cache=false
spring.thymeleaf.enabled=false
数据库连接核心设置:
usSSL=false:
MySQL在高版本需要指明是否进行SSL连接。
JDBC版本与MySQL版本不兼容,MySQL的版本更高一些,在连接语句后加上“useSSL=‘true’” ,就可以连接到数据库了。
spring.datasource.url=jdbc:mysql://localhost:3306/db_mysql?useSSL=false
spring.datasource.username=root
spring.datasource.password=mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
声明jpa规范;
JPA:实际上就是实体Bean的一个规范;
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。