<> one , Create a Maven project
<> two , Import coordinates
stay pom.xml Add the following coordinates , And click the top right corner to refresh .
<dependencies> <dependency> <groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId> <version>5.3.15</version> </dependency>
<dependency> <groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId> <version>5.3.15</version> </dependency>
<dependency> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <version>8.0.25</version>
</dependency> </dependencies>
<> three , trusteeship DataSource class
Create a file named AppConfig class . trusteeship DataSource class , add @Configuration annotation . Pay attention to setting the specified connection to the database url, user name , And password .
import org.springframework.context.annotation.Bean; import
org.springframework.context.annotation.Configuration; import
org.springframework.jdbc.datasource.DriverManagerDataSource; import
javax.sql.DataSource; @Configuration public class AppConfig { @Bean public
DataSource dataSource(){ DriverManagerDataSource d = new
DriverManagerDataSource() ;
d.setUrl("jdbc:mysql://localhost:3306/test?serverTimezone=UTC"); // set up url //
Above test For your database name d.setUsername("root"); // Set account d.setPassword("root"); // Set password
return d; } }
<> four , test
Create a Test class . adopt DataSource Get database connection . And output .
import org.springframework.context.ApplicationContext; import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
import javax.sql.DataSource; import java.sql.Connection; import
java.sql.SQLException; public class Test { public static void main(String[]
args) throws SQLException { ApplicationContext ac = new
AnnotationConfigApplicationContext(AppConfig.class); DataSource d =
(DataSource) ac.getBean("dataSource"); Connection c = d.getConnection(); // Get connection
System.out.println(c); } }
The following code appears on the console , The connection is successful .
Technology
Daily Recommendation