Java SpringJDBC将数据源注入另一个bean

Java SpringJDBC将数据源注入另一个bean,java,spring,jdbc,Java,Spring,Jdbc,我是春天的新手。在学习的过程中,我决定使用JDBC 简而言之,我有两门课: 第1类包含以下内容: import javax.sql.DataSource; public class class1 extends class2 { private Connection con; private DataSource dataSource; public void setDataSource(DataSource ds) { dataSource = ds

我是春天的新手。在学习的过程中,我决定使用JDBC

简而言之,我有两门课:

第1类包含以下内容:

import javax.sql.DataSource;
public class class1 extends class2 {

    private Connection con;
    private DataSource dataSource;

    public void setDataSource(DataSource ds) {
        dataSource = ds;
    }

public void getConnection(){
login(username,password,url);
con = dataSource.getConnection();
}
}
类1基本上是我要求用户输入用户名/密码/ur,然后从类2中调用传递这些细节的方法。我想将DataSource的值从这个类注入到class1。到目前为止,这是我的class2代码:

import javax.sql.DataSource;

import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

abstract class class2{
public void login(String username, String password, String url){
GenericApplicationContext context = new GenericApplicationContext();
            DefaultListableBeanFactory factory = (DefaultListableBeanFactory) context.getBeanFactory();

            BeanDefinitionBuilder bean1 = BeanDefinitionBuilder
                    .rootBeanDefinition("org.springframework.jdbc.datasource.DriverManagerDataSource");
            bean1.addPropertyReference("driverClassName", "dataSource");
            bean1.addPropertyValue("driverClassName", "com.mysql.jdbc.Driver");
            bean1.addPropertyReference("url", "dataSource");
            bean1.addPropertyValue("url", "url");
            bean1.addPropertyReference("username", "dataSource");
            bean1.addPropertyValue("username", username);
            bean1.addPropertyReference("password", "dataSource");
            bean1.addPropertyValue("password", password);
            bean1.registerBeanDefinition("dataSource", bean1.getBeanDefinition());

            BeanDefinitionBuilder bean2 = BeanDefinitionBuilder.rootBeanDefinition("class2");
            bean2.addPropertyValue("dataSource", "getCon");
            context.refresh();
            bean2.addPropertyValue("dataSource", new RuntimeBeanReference("dataSource"));

            factory.registerBeanDefinition("getCon", bean2.getBeanDefinition());

}
}
然而,当我尝试执行class1中的方法
getConnection()
时,它给出了NPE。有人能告诉我正确的方法吗


另外,我希望通过编程(而不是使用xml)来完成这项任务。

如果您想在Spring中完成这项任务,那么您需要在应用程序上下文xml中声明一个bean定义,以创建数据源并注入到您的类中

或者,您可以使用SpringJDBC创建数据源。查看此链接:


如果您想用弹簧方式执行此操作,您需要阅读文档。然而,既然你已经向Spring陈述了你的新想法,我强烈建议你从Uhhh开始。我已经使用Spring有一段时间了,但是这些课程让我怀疑我在这个主题上的知识水平。关于Spring Boot的建议:我不会建议某人在不了解DI的基本概念的情况下开始使用它。从“顶部”开始让人们觉得这是一个纯粹的魔术。向我们展示NPE,告诉我们它发生在哪一行