【问题标题】:Alternative to static JdbcTemplate in SpringSpring中静态JdbcTemplate的替代方案
【发布时间】:2017-09-28 05:50:57
【问题描述】:

我已经在 Spring 中实现了抽象 DAO 工厂。

我有两种自动装配方法如下:

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 中是否有任何替代 static 的方法?

【问题讨论】:

  • 您不应该使用 new 来获取 Spring 组件。这就是错误。您应该使用依赖注入,这就是 Spring 的全部意义所在。
  • 如果你将 jdbcTemplate 和 dataSource 字段设为@Autowired,那么 spring 会管理这些对象的生命周期。你不应该创建封闭类的实例。

标签: java spring spring-mvc autowired jdbctemplate


【解决方案1】:

你应该在你的类之上使用@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();
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多