Spring 使用 properties 文件两种读取方式:xml 直接读取和 @Value 注解获取
因为我们在交付项目时,我们不应该再让用户去修改代码去配置,但是我们经常需要用户去配置一些自己的内容,不管是对用户保密的也好,让用户自定义也好,肯定有需要用户去定义的部分
常见使用环境:
(1)最经常用到的就是数据库连接配置,用户名密码
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/数据库名?serverTimezone=UTC
jdbc.user=用户名
jdbc.password=密码
(2)还有就是用的一些存储路径
file.upload.location=D:/workspace/Team10/user_file
第一步:加载 properties 文件
只有加载到项目中,才能使用
<context:property-placeholder location="classpath*:jdbcConfig.properties"/>
也可以使用其属性,提升对用户输入内容,容错性
<context:property-placeholder location="classpath*:jdbcConfig.properties" ignore-unresolvable="true"/>
第二步:读取 properties 文件变量
(1)XML 文件直接使用:
不管是哪种方式,加载完只有都可以使用了,例如
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
(2)在 Controller 等层使用 @Value 注解读取:
只能作为全局变量,不清楚,下方有示例
//读取properties文件位置变量
@Value("${file.upload.location}")
String realPath;
【注意】:不能放在内部方法里面作为本地变量使用,只能放在public类中,直接作为全局变量使用,例如:
@RestController
@RequestMapping("/logic/studentProject")
public class DspStudentReportController {
@Autowired
@Qualifier("dspTeacherStudentServiceImpl")
private IDspTeacherStudentService dspTeacherStudentService;
//读取properties文件位置变量
@Value("${file.upload.location}")
String realPath;
}