Java Spring中静态JdbcTemplate的替代方案

Java Spring中静态JdbcTemplate的替代方案,java,spring,spring-mvc,autowired,jdbctemplate,Java,Spring,Spring Mvc,Autowired,Jdbctemplate,我已经在春天实现了抽象刀工厂 我有两种自动连线方法,如下所示: private DataSource dataSource; private JdbcTemplate jdbcTemplate; @Autowired public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Autowired public void setDataSource(

我已经在春天实现了抽象刀工厂

我有两种自动连线方法,如下所示:

private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

@Autowired

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

    this.jdbcTemplate = jdbcTemplate;
}


@Autowired

 public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}
在开始时,jdbcTemplate和dataSource在其中获得正确的值。但是,当我使用new关键字调用类的构造函数时(在该关键字中编写了上述方法),jdbcTemplate和dataSource被设置为NULL

但是如果我将它们声明为静态,那么之前正确的值将被保留


我想知道如果我想保留上面两个的值,在spring中是否有静态的替代方法

您应该在类的顶部添加@Component,以获取dataSource和jdbcTemplate的对象值。您不应该使用类的new关键字来获取自动连接的引用

下面的代码可能有助于回答您的问题

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

@Configuration
@ComponentScan("com.ledara.demo")
public class ApplicationConfig {

    @Bean
    public DataSource getDataSource() {
        DriverManagerDataSource dmds = new DriverManagerDataSource();
        dmds.setDriverClassName("com.mysql.jdbc.Driver");
        dmds.setUrl("yourdburl");
        dmds.setUsername("yourdbusername");
        dmds.setPassword("yourpassword");
        return dmds;
    }

    @Bean
    public JdbcTemplate getJdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
        return jdbcTemplate;
    }

}
下面的类有jdbcTemplate和dataSource的自动连接字段

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class SampleInfo{

    @Autowired(required=true)
    DataSource getDataSource;

    @Autowired(required=true)
    JdbcTemplate getJdbcTemplate;

    public void callInfo() {
        System.out.println(getDataSource);
        System.out.println(getJdbcTemplate);

    }

} 
下面是主课

public class MainInfo {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(ApplicationConfig.class);
        context.refresh();
        SampleInfo si=context.getBean(SampleInfo.class);
        si.callInfo();
    }

}

您不应该使用new来获取弹簧组件。这是个错误。您应该使用依赖项注入,这就是Spring的全部内容。如果您将jdbcTemplate和dataSource字段设置为@Autowired,那么Spring将管理这些对象的生命周期。您不应该创建封闭类的实例。