spring的配置类的使用
在配置文件配置
jdbc.url=127.0.0.1:3306/test
jdbc.user=test
jdbc.password=test
jdbc.driver=com.mysql.cj.jdbc.Driver
配置文件的bean
@Configuration
说明这是配置类
@PropertySource(value = “classpath:application.properties”)
引入配置文件地址
@Value指定配置文件指定的key对应哪个属性。
package com.example.demo.conf;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource(value = "classpath:application.properties")
public class JDBCProperties {
@Value("${jdbc.url}")
public String url;
@Value("${jdbc.user}")
public String user;
@Value("${jdbc.password}")
public String password;
@Value("${jdbc.driver}")
public String driver;
}
调用直接将配置类注入,就可以取到。
@Autowired
JDBCProperties properties;
@GetMapping("testJdbc")
public void testJdbc(){
String driver = properties.driver;
System.out.println(driver);
}