我在春季实现了Abstract DAO Factory。
我有两种自动接线方法,如下所示:
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。
但是,如果我将它们声明为静态,则保留先前的正确值。
我想知道如果我想保留上述两个的以前的值,那么在春季是否有替代静态的方法?
您应该在类顶部使用@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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句