使用 Spring JDBC 连接到数据库

Connecting to database using Spring JDBC

我正在尝试使用 Spring JDBC

连接到我的数据库

Beans.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5434/lab1_aop" />
        <property name="username" value="postgres" />
        <property name="password" value="passw" />
   </bean>

</beans>

我要连接的地方:

public class BookService { 
    private Connection connection;

    public BookService() {
         ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
    }
}

我收到这些错误

The constructor ClassPathXmlApplicationContext(String) refers to the missing type BeansException    BookService.java
The type org.springframework.beans.BeansException cannot be resolved. It is indirectly referenced from required .class files

我做错了什么?

看起来,您的项目中缺少一些 Spring Jar!使用任何标准的依赖关系管理工具,如 Gradle、Maven 或 Ant 来解决您的依赖关系。

在这里您可以找到如何配置 Spring project using Gradle 的示例。

如果你使用maven,你需要添加spring-contextspring-beans依赖。

为了更好的依赖管理使用maven or gradle

加入pom.xml:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>{spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>{spring.version}</version>
    </dependency>