因此,根据 Azure 中的文档:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
public class AADServicePrincipal {
public static void main(String[] args) throws Exception{
String principalId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your AAD service principal ID.
String principalSecret = "..."; // Replace with your AAD principal secret.
SQLServerDataSource ds = new SQLServerDataSource();
ds.setServerName("aad-managed-demo.database.windows.net"); // Replace with your server name
ds.setDatabaseName("demo"); // Replace with your database
ds.setAuthentication("ActiveDirectoryServicePrincipal");
ds.setAADSecurePrincipalId(principalId);
ds.setAADSecurePrincipalSecret(principalSecret);
try (Connection connection = ds.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
if (rs.next()) {
System.out.println("You have successfully logged on as: " + rs.getString(1));
}
}
}
}
我们可以使用它来创建一个可以通过 AD 服务主体连接到 SQL Server 的数据源,并将其作为 bean 插入,我相信它是:
@Bean
@Primary
DataSource dataSource() throws SQLException {
String principalId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your AAD service principal ID.
String principalSecret = "..."; // Replace with your AAD principal secret.
SQLServerDataSource ds = new SQLServerDataSource();
ds.setServerName("aad-managed-demo.database.windows.net"); // Replace with your server name
ds.setDatabaseName("demo"); // Replace with your database
ds.setAuthentication("ActiveDirectoryServicePrincipal");
ds.setAADSecurePrincipalId(principalId);
ds.setAADSecurePrincipalSecret(principalSecret);
return ds;
}
但我正在寻找的是 - 我们可以通过 YAML/application.properties 配置整个事情,以便使用 Data JPA 自动配置吗?如果没有,上述过程可以工作吗?