一、配置属性
在application.properties文件中增加属性:
server.port=80
user.name=帅B
二、读取配置文件参数
1.注解方式读取
1)设置配置文件路径
在类上添加注解,如果在默认路径下可以不添加该注解。classpath:my.properties指的是src/main/resources目录下的my.properties文件。
//多配置文件引用,若取两个配置文件中有相同属性名的值,则取值为最后一个配置文件中的值
@PropertySource({"classpath:config/my.properties","classpath:config/config.properties"})
public class TestController
2)设置要读取的配置文件属性
@Value属性名,在属性名上添加该注解
@Value("${user.name}")
private String userName;
2.对象映射方式读取(使用注释处理器)
1)pom文件中引入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2)新建配置文件my.properties(非必须)
使用此种方式时,自定义属性的命名规则:小写字母数字组合,必须以小写字母开头,可用分隔符"-"
#自定义属性读取
user-info.name=帅比
user-info.age=30
user-info.eye[0]=4.8
user-info.eye[1]=4.9
3)新建对象,设置与配置文件的映射关系
@Component
@PropertySource("classpath:my.properties")
@ConfigurationProperties(prefix = "user-info")//配置文件中的前缀
@Data//lombook下节讲
public class MyProperties {
private String name;
private int age;
//集合必须初始化,如果找不到就是空集合,会报错
private List<String> eye = new ArrayList<>();
}
4)通过注解方式使用,可直接读取其属性
@Autowired
private MyProperties myProperties;
tips:
如果项目中用到AspectJ,则需要确保注释处理器只运行一次。借助Maven,可明确配置maven-apt-plugin并且仅在那里将依赖关系添加到注释器。还可以让AspectJ插件运行所有处理并禁用maven-compiler-plugin配置中的注释处理,如下所示:
<plugin>
<groupId> org.apache.maven.plugins </ groupId>
<artifactId> maven-compiler-plugin </ artifactId>
<configuration>
<proc> none </ proc>
</ configuration>
</ plugin>
三、解决中文乱码
1.修改properties文件本身的编码方式,使得中文就显示中文
2.修改读取属性值返回给前端的编码方式,使得中文正常显示
![](https://img.haomeiwen.com/i9261625/05ed5674c60a92cc.png)
网友评论