yml配置mysql

在开发中,配置文件是非常重要的一部分。在使用MySQL数据库时,我们通常需要配置数据库连接信息,包括数据库地址、端口号、用户名、密码等。在Java开发中,我们可以使用yml文件来配置MySQL数据库,方便管理和维护。
创建yml文件
首先,我们需要在项目的resources目录下创建一个名为application.yml的yml文件。在这个文件中,我们可以配置MySQL连接信息,示例如下:
spring:
datasource:
url: jdbc:mysql://localhost:3306/testdb
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
在这段配置中,我们配置了MySQL的连接地址为localhost,端口为3306,数据库名为testdb。用户名为root,密码为123456。driver-class-name为MySQL的驱动类。
配置数据库连接信息
在Spring Boot项目中,我们可以使用@ConfigurationProperties注解将yml文件中的配置信息读取到Java类中。示例如下:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DatabaseConfig {
private String url;
private String username;
private String password;
private String driverClassName;
// getter and setter methods
}
在这个类中,我们使用@ConfigurationProperties注解定义了前缀为spring.datasource,这样在yml文件中的配置信息就会被读取到这个类中。然后我们可以在其他地方注入这个类,获取配置信息。
使用数据库连接信息
在Spring Boot项目中,我们可以通过@Autowired注解将配置信息注入到需要使用的地方,示例如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DatabaseService {
@Autowired
private DatabaseConfig databaseConfig;
public void connectDatabase() {
System.out.println("Connecting to database...");
System.out.println("URL: " + databaseConfig.getUrl());
System.out.println("Username: " + databaseConfig.getUsername());
System.out.println("Password: " + databaseConfig.getPassword());
System.out.println("Driver Class Name: " + databaseConfig.getDriverClassName());
}
}
在这个类中,我们使用@Autowired注解将DatabaseConfig类注入到DatabaseService类中。然后我们就可以通过DatabaseConfig类获取到配置信息,连接数据库。
运行结果
当我们配置好了yml文件,并且编写了相应的Java类后,我们就可以在项目中运行代码,看到数据库连接信息。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
DatabaseService databaseService = new DatabaseService();
databaseService.connectDatabase();
}
}
在运行时,我们会看到输出的数据库连接信息,如下:
Connecting to database...
URL: jdbc:mysql://localhost:3306/testdb
Username: root
Password: 123456
Driver Class Name: com.mysql.cj.jdbc.Driver
通过这样的配置,我们可以方便地管理数据库连接信息,从而更好地开发项目。
极客教程