1.@PropertySource
@PropertySource:加载指定的配置文件【properties】.
先前我们通过@ConfifigurationProperties加载全局配置文件[appliaction.properties]中的值到javabean中,但是我们在具体使用的时候不会把所用的配置都保存在全局配置文件中的,可能会将不同的配置保存在不同的配置文件中,那么这时我们就需要@PropertySource注解为指定的javabean类加载指定的配置文件
例如:
package com.wangxing.springboot.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
//@ConfigurationProperties(prefix = "student")
//此出不用使用前缀使用为使用了value注解 value注解中也含有@Retention注解所以@ConfigurationProperties注解不用使用
@PropertySource("classpath:studnetbean.properties")
public class StudentBean {
@Value("${student.id}")
private int stuid;
@Value("${student.name}")
private String stuname;
@Value("${student.sex}")
private boolean stusex;
@Value("${student.height}")
private double stuheight;
public int getStuid() {
return stuid;
}
public void setStuid(int stuid) {
this.stuid = stuid;
}
public String getStuname() {
return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public boolean isStusex() {
return stusex;
}
public void setStusex(boolean stusex) {
this.stusex = stusex;
}
public double getStuheight() {
return stuheight;
}
public void setStuheight(double stuheight) {
this.stuheight = stuheight;
}
}
package com.wangxing.springboot.controller;
import com.wangxing.springboot.bean.StudentBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/testStudnet")
public class StudnetController {
@Autowired
private StudentBean studentBean;
@RequestMapping("/testPropertySource.do")
public void testPropertySource(){
int stuid = studentBean.getStuid();
String stuname = studentBean.getStuname();
boolean stusex = studentBean.isStusex();
double stuhieght = studentBean.getStuheight();
System.out.println(stuid+","+stuname+","+stusex+","+stuhieght);
}
}
student.id=1001
student.name="zhangsan"
student.sex=false
student.height=168.5
127.0.0.1:8080/testStudnet/testPropertySource.do
personBean
package com.wangxing.springboot.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
//设置配置文件中的前缀若要使用自定义的配置文件则前缀必须写,并且不能有大写字母
@ConfigurationProperties(prefix = "personbean")
@PropertySource(value = "classpath:personbean.properties")
public class PersonBean {
private int perid;
private String pername;
private boolean persex;
private double pergeight;
public int getPerid() {
return perid;
}
public void setPerid(int perid) {
this.perid = perid;
}
public String getPername() {
return pername;
}
public void setPername(String pername) {
this.pername = pername;
}
public boolean isPersex() {
return persex;
}
public void setPersex(boolean persex) {
this.persex = persex;
}
public double getPergeight() {
return pergeight;
}
public void setPergeight(double pergeight) {
this.pergeight = pergeight;
}
}
package com.wangxing.springboot.controller;
import com.wangxing.springboot.bean.PersonBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/testperson")
public class PersonController {
@Autowired
private PersonBean personBean;
@RequestMapping("/testPropertySource.do")
public void testPropertySource(){
int perid = personBean.getPerid();
String pername = personBean.getPername();
boolean persex = personBean.isPersex();
double perheigth = personBean.getPergeight();
System.out.println(perid+"," + pername+ ","+persex + ","+perheigth + ",");
}
}
#person.perid=1002
#person.pername="lisisi"
#person.persex=true
#person.pergeight=179.8
#personbean
personbean.perid=1002
personbean.pername="lisisi"
personbean.persex=true
personbean.pergeight=179.8
127.0.0.1:8080/testperson/testPropertySource.do
名称 | 用途 |
@PropertySource(value = "classpath:studentbean.properties") | 标注在类上,指定的配置文件【properties】,可以引入多个配置文件,例如 @PropertySource({ "classpath:studentbean.properties", "classpath:person.properties"}) |
@Value("${xxxx}") | 标注在成员变量上,设置当前成员变量的初始值,可以直接设值@Value("zhangsan"),也可以从@PropertySource指定的配置文件【properties】中取值设置给成员变量@Value("${xxxx}") |
@ConfigurationProperties(prefix = "person") | 标注在类上,表示设置当前类在配置文件【properties】的配置名称【prefix = "person"】(使用这个注解可以将自己定义的配置文件加载,生成一个帮助文件,也就是会有自动提示,所以要想有自动提示,需要加上这个注解) |
2.@ImportResource
@ImportResource:导入基于XML的Spring的配置文件,让配置文件里面的内容生效;
@ImportResource标注在一个主类上
package com.wangxing.springboot.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
//@Component
@ConfigurationProperties("user")
@PropertySource("classpath:userbean.properties")
public class UserBean {
// @Value("${user.id}")
private int userId;
// @Value("${user.name}")
private String userName;
// @Value("${user.sex}")
private boolean userSex;
// @Value("${user.height}")
private double userHeight;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public boolean isUserSex() {
return userSex;
}
public void setUserSex(boolean userSex) {
this.userSex = userSex;
}
public double getUserHeight() {
return userHeight;
}
public void setUserHeight(double userHeight) {
this.userHeight = userHeight;
}
}
package com.wangxing.springboot.controller;
import com.wangxing.springboot.bean.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping(value = "/testUserBean")
@RestController
public class UserController {
@Autowired
private UserBean userBean;
@RequestMapping("/testPropertySource.do")
public void testPropertySource(){
int userid=userBean.getUserId();
String username=userBean.getUserName();
boolean usersex=userBean.isUserSex();
double userheight=userBean.getUserHeight();
System.out.println(userid+","+username+"?,"+usersex+","+userheight);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userBean" class="com.wangxing.springboot.bean.UserBean">
<!-- <property name="userId" value="10011"></property>-->
<property name="userId" value="${user.id}"></property>
<property name="userName" value="${user.name}"></property>
<property name="userSex" value="${user.sex}"></property>
<property name="userHeight" value="${user.height}"></property>
</bean>
</beans>
userbean.properties
user.id=1111
user.xingming=lisi
user.sex=true
user.height=170.01
package com.wangxing.springboot.demo1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Component;
@SpringBootApplication
@ComponentScan(basePackages = "com.wangxing.springboot")
@ImportResource(value = "classpath:userbean.xml")
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
这样写会报错,
Invalid bean definition with name 'userBean' defined in class path resource [userbean.xml]: Could not resolve placeholder 'user.id' in value "${user.id}";
-
非法参数异常
nested exception is java.lang.IllegalArgumentException:
Could not resolve placeholder 'user.id' in value "${user.id}"
也就是说java程序无法识别表达式中的参数
,通过点击参数我发现可以跳转,那么问题可能出在导入上,因为没有将配置文件导入进来所以无法使用
//@ConfigurationProperties("user")
//@PropertySource("classpath:userbean.properties")
使用注解的方式导入在spring配置文件中是无法被加载到的,将注解注释掉,
在spring配置文件中导入属性文件
需要头文件中加上命名空间注解
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
使用这个元素
<context:property-placeholder location="classpath:userbean.properties"></context:property-placeholder>
userbean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:userbean.properties"></context:property-placeholder>
<bean id="userBean" class="com.wangxing.springboot.bean.UserBean">
<!-- <property name="userId" value="10011"></property>-->
<property name="userId" value="${user.id}"></property>
<property name="userName" value="${user.xingming}"></property>
<property name="userSex" value="${user.sex}"></property>
<property name="userHeight" value="${user.height}"></property>
</bean>
</beans>
在配置文件的EL表达式中使用username / user.name
都会获得你的电脑账户名
所以将获取用户名的El表达式改为
${user.xingming}
这个可能和spring的内置配置有关
Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;
想让Spring的配置文件生效,加载进来.
使用@ImportResource(value = "classpath:userbean.xml")这个注解加载
3.@Configuration @Bean @Import
package com.wangxing.springboot.bean;
public class UserBean {
private int userId;
private String userName;
private double userDouble;
private boolean userSex;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public double getUserDouble() {
return userDouble;
}
public void setUserDouble(double userDouble) {
this.userDouble = userDouble;
}
public boolean isUserSex() {
return userSex;
}
public void setUserSex(boolean userSex) {
this.userSex = userSex;
}
}
UserConfig
package com.wangxing.springboot.config;
import com.wangxing.springboot.bean.UserBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class UserConfig {
@Bean
public UserBean getBean(){
UserBean userBean = new UserBean();
userBean.setUserId(1001);
userBean.setUserName("zhangsan");
userBean.setUserDouble(123.3);
userBean.setUserSex(true);
return userBean;
}
}
UserController
package com.wangxing.springboot.controller;
import com.wangxing.springboot.bean.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/user")
@RestController
public class UserController {
@Autowired
private UserBean userBean;
@RequestMapping("/testuserbean.do")
public void testUserBena(){
int userId = userBean.getUserId();
String userName = userBean.getUserName();
double userDouble = userBean.getUserDouble();
boolean usersex = userBean.isUserSex();
System.out.println(userId+","+userName+","+userDouble+","+usersex);
}
}
package com.wangxing.springboot.demo2;
import com.wangxing.springboot.config.UserConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@ComponentScan("com.wangxing.springboot")
@Import(UserConfig.class)
public class Demo2Application {
public static void main(String[] args) {
SpringApplication.run(Demo2Application.class, args);
}
}
名称 | 用途 |
@Configuration | 标注在类上,表示当前类是一个java Config形式的配置类,可以代替基于xml的配置文件 |
@Bean | 标注在方法上,告诉springIOC容器创建javabean类对象 相当于在基于xml配置文件中的 <bean id=”” class=””></bean> |
@Import(xxxConfig.class) | 标注在主类上,表示导入xxxConfig.class【java Config形式的配置类】 |
4.Profiles
- Profifile文件就是用来配置在不同环境下的配置数据。
- 因为在不同的环境下配置文件中配置的运行环境的数据是不同的,所以我们就需要灵活的在不同的运行环境下切换成对应的运行环境的数据,此时我们将不同的运行环境数据,配置到不同的配置文件中,通过在主配置文件application.properties中的spring.profiles.active属性完成切换。
测试.properties配置
application-dev.properties【开发环境配置】
server.port=8080
application-prod.properties【生产环境配置】
server.port=9090
application.properties 【主配置】
spring.profiles.active=prod 【指定使用生产环境配置】
或者
spring.profiles.active=dev 【指定使用开发环境配置】
测试.yml配置
application-devyml.yml【开发环境配置】
server:
port: 8080
application-prodyml.yml【生产环境配置】
server:
port: 9090
application.yml 【主配置】
spring:
profiles:
active: prodyml 【指定使用生产环境配置】
或者
spring:
profiles:
active: devyml 【指定使用开发环境配置】
上面是通过在1.主配置文件中切换运行环境配置
还可以通过配置2.运行环境参数配置视图窗口来指定具体使用哪一个运行环境
“--spring.profiles.active=dev“
还可以通过3.命令行运行jar的时候指定具体使用哪一个运行环境
java -jar testspringboot002-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
还可以通过4.配置虚拟机参数指定具体使用哪一个运行环境;
“-Dspring.profiles.active=dev”
注意:运行环境配置文件的名称 application-{profiles}.properties/yml
5.主配置文件加载位置
spring boot 启动会扫描以下位置的application.properties或者 application.yml文件作为Spring boot的默认配置文件
– 项目根目录/config/
– 项目根目录/
– resource/config/
– resource:/
以上是按照优先级从高到低的顺序,所有位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置内容。
SpringBoot会从这四个位置全部加载主配置文件;互补配置
我们也可以通过配置spring.config.location来改变默认配置
项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置,指定配置文件和默认加载的这些配置文件共同起作用形成互补配置;
java -jar testspringboot02-0.0.1-SNAPSHOT.jar --spring.confifig.location=F:/application.properties
6.外部配置加载顺序
Spring Boot 支持多种外部配置方式
1. 命令行参数
2. 来自java:comp/env的JNDI属性
3. Java系统属性(System.getProperties())
4. 操作系统环境变量
5. RandomValuePropertySource配置的random.*属性值
6. jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
7. jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
8. jar包外部的application.properties或application.yml(不带spring.profile)配置文件
9. jar包内部的application.properties或application.yml(不带spring.profile)配置文件
优先加载带profifile,再来加载不带profifile,由jar包外向jar包内进行寻找
10. @Configuration注解类上的@PropertySource
11. 通过SpringApplication.setDefaultProperties指定的默认属性