简体   繁体   English

Spring启动jdbc连接

[英]Spring boot jdbc Connection

i'm trying to configure spring boot in order to have tomcat connection pool to my production database. 我正在尝试配置spring boot以便将tomcat连接池连接到我的生产数据库。 My application is NOT web (i have also some difficult to tell that to spring). 我的应用程序不是网络(我也有一些很难说春天)。

I have a Startup class and 3 more classes 我有一个Startup类和另外3个类

the code 编码

@Configuration

@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)

public class Starter {

private static Logger logger;

@Autowired
private static MyController controller;

public static void main(String[] args) {

//      SpringApplication.setWebEnvironment(false);

    SpringApplication.run(Starter.class, args);

    LogbackConfigLoader lcl = new LogbackConfigLoader();
    if (lcl.init()) {
        logger = LoggerFactory.getLogger(Starter.class);
        logger.debug("Initialized....");
    }
    else{
        logger = LoggerFactory.getLogger(Starter.class);
    }


    logger.info(controller.getProva());

}


}

here is the configuration ` 这是配置`

@Configuration

@ConfigurationProperties(prefix="datasource.NIS")

public class NISDBConfiguration {

private String jdbcInterceptors;
private long validationInterval = 30000;

private org.apache.tomcat.jdbc.pool.DataSource pool;

@Value("${driver-class-name}")
private String driverClassName;

@Value("${url}")
private String url;

@Value("${username}")
private String username;

@Value("${password}")
private String password;

@Value("${maxActive}")
private int maxActive = 30;

@Value("${maxIdle}")
private int maxIdle = 8;

@Value("${minIdle}")
private int minIdle = 8;

@Value("${initialSize}")
private int initialSize = 10;

private String validationQuery;

private boolean testOnBorrow;

private boolean testOnReturn;

private boolean testWhileIdle;

private Integer timeBetweenEvictionRunsMillis;

private Integer minEvictableIdleTimeMillis;

private Integer maxWaitMillis;

public String getJdbcInterceptors() {
    return jdbcInterceptors;
}

public void setJdbcInterceptors(String jdbcInterceptors) {
    this.jdbcInterceptors = jdbcInterceptors;
}

public long getValidationInterval() {
    return validationInterval;
}

public void setValidationInterval(long validationInterval) {
    this.validationInterval = validationInterval;
}

public org.apache.tomcat.jdbc.pool.DataSource getPool() {
    return pool;
}

public void setPool(org.apache.tomcat.jdbc.pool.DataSource pool) {
    this.pool = pool;
}

public String getDriverClassName() {
    return driverClassName;
}

public void setDriverClassName(String driverClassName) {
    this.driverClassName = driverClassName;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public int getMaxActive() {
    return maxActive;
}

public void setMaxActive(int maxActive) {
    this.maxActive = maxActive;
}

public int getMaxIdle() {
    return maxIdle;
}

public void setMaxIdle(int maxIdle) {
    this.maxIdle = maxIdle;
}

public int getMinIdle() {
    return minIdle;
}

public void setMinIdle(int minIdle) {
    this.minIdle = minIdle;
}

public int getInitialSize() {
    return initialSize;
}

public void setInitialSize(int initialSize) {
    this.initialSize = initialSize;
}

public String getValidationQuery() {
    return validationQuery;
}

public void setValidationQuery(String validationQuery) {
    this.validationQuery = validationQuery;
}

public boolean isTestOnBorrow() {
    return testOnBorrow;
}

public void setTestOnBorrow(boolean testOnBorrow) {
    this.testOnBorrow = testOnBorrow;
}

public boolean isTestOnReturn() {
    return testOnReturn;
}

public void setTestOnReturn(boolean testOnReturn) {
    this.testOnReturn = testOnReturn;
}

public boolean isTestWhileIdle() {
    return testWhileIdle;
}

public void setTestWhileIdle(boolean testWhileIdle) {
    this.testWhileIdle = testWhileIdle;
}

public Integer getTimeBetweenEvictionRunsMillis() {
    return timeBetweenEvictionRunsMillis;
}

public void setTimeBetweenEvictionRunsMillis(
        Integer timeBetweenEvictionRunsMillis) {
    this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}

public Integer getMinEvictableIdleTimeMillis() {
    return minEvictableIdleTimeMillis;
}

public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
    this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}

public Integer getMaxWaitMillis() {
    return maxWaitMillis;
}

public void setMaxWaitMillis(Integer maxWaitMillis) {
    this.maxWaitMillis = maxWaitMillis;
} 

@Bean(name = "dsNIS") 
public DataSource dataSource() { 
    this.pool = new org.apache.tomcat.jdbc.pool.DataSource();
    this.pool.setDriverClassName(getDriverClassName());
    this.pool.setUrl(getUrl());
    this.pool.setUsername(getUsername());
    this.pool.setPassword(getPassword());
    this.pool.setInitialSize(getInitialSize());
    this.pool.setMaxActive(getMaxActive());
    this.pool.setMaxIdle(getMaxIdle());
    this.pool.setMinIdle(getMinIdle());
    this.pool.setTestOnBorrow(isTestOnBorrow());
    this.pool.setTestOnReturn(isTestOnReturn());
    this.pool.setTestWhileIdle(isTestWhileIdle());

    if (getTimeBetweenEvictionRunsMillis() != null) {
        this.pool
                .setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis());
    }
    if (getMinEvictableIdleTimeMillis() != null) {
        this.pool.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis());
    }
    this.pool.setValidationQuery(getValidationQuery());
    this.pool.setValidationInterval(this.validationInterval);
    if (getMaxWaitMillis() != null) {
        this.pool.setMaxWait(getMaxWaitMillis());
    }
    if (this.jdbcInterceptors != null) {
        this.pool.setJdbcInterceptors(this.jdbcInterceptors);
    }
    return this.pool;

} 

@PreDestroy
public void close() {
    if (this.pool != null) {
        this.pool.close();
    }
}

@Bean(name = "jdbcNIS") 
public JdbcTemplate jdbcTemplate(DataSource dsNIS) { 
    return new JdbcTemplate(dsNIS); 
}

} ` }

the repository 存储库

package org.hp.data;

@Repository

public class NisRepository {

protected final Logger log = LoggerFactory.getLogger(getClass()); 


@Autowired 
@Qualifier("jdbcNIS") 
protected JdbcTemplate jdbc; 


public String getItem(long id) { 
    return jdbc.queryForObject("SELECT * FROM sb_item WHERE id=?", itemMapper, id); 
} 

private static final RowMapper<String> itemMapper = new RowMapper<String>() {
    @Override
    public String mapRow(ResultSet rs, int rowNum) throws SQLException { 
        String item = rs.getString("title"); 
        return item; 
    } 
};


public JdbcTemplate getJdbc() {
    return jdbc;
}

public void setJdbc(JdbcTemplate jdbc) {
    this.jdbc = jdbc;
} 

} }

the controller 控制器

@Controller
public class MyController {


@Autowired 
private NisRepository items; 

public NisRepository getItems() {
    return items;
}

public void setItems(NisRepository items) {
    this.items = items;
}

public String getProva(){
    return items.getItem(10);
}

} }

But i always get exception when running the application of NullPointerException because MyController is not autowired and is always null. 但是在运行NullPointerException应用程序时总是会出现异常,因为MyController不是自动装配的,并且始终为null。

I also try to create a new instance with new (but i believe that this is not correct because of the spring mvc pattern). 我也尝试用new创建一个新实例(但我相信这是不正确的,因为spring mvc模式)。

What is the problem here? 这里有什么问题?

Thanks in advance 提前致谢

You are using Spring Boot but are trying very hard not to use it. 您正在使用Spring Boot,但我们正在努力不使用它。 You also state you aren't using a web application but then why do you have a @Controller ? 您还声明您没有使用Web应用程序,但为什么您有@Controller

To fix your problem remove the configuration of the DataSource and JdbcTemplate Spring Boot will configure those for you. 要解决您的问题,请删除DataSourceJdbcTemplate配置Spring Boot将为您配置这些配置。 This basically means remove your NISDBConfiguration class. 这基本上意味着删除你的NISDBConfiguration类。 Just add the correct properties to the application.properties file. 只需将正确的属性添加到application.properties文件即可。

spring.datasource.driver-class-name=<your-driver-here>
spring.datasource.url=<your-url>
spring.datasource.username=<your-username>
spring.datasource.password=<your-password>

And of course the other properties you need, check the reference guide for more properties. 当然还有您需要的其他属性,请查看参考指南以获取更多属性。

Remove the @Qualifier from the JdbcTemplate property in your repository and you also don't need the getter and setter. 从存储库中的JdbcTemplate属性中删除@Qualifier ,您也不需要getter和setter。 I would suggest using constructor based injection. 我建议使用基于构造函数的注入。

package org.hp.data;

@Repository
public class NisRepository {

    protected final Logger log = LoggerFactory.getLogger(getClass()); 

    protected final JdbcTemplate jdbc; 

    @Autowired
    public NisRepository(JdbcTemplate jbc) {
        this.jdbc=jdbc;
    }

    public String getItem(long id) { 
        return jdbc.queryForObject("SELECT * FROM sb_item WHERE id=?", itemMapper, id); 
    } 


    private static final RowMapper<String> itemMapper = new RowMapper<String>() {
        @Override
        public String mapRow(ResultSet rs, int rowNum) throws SQLException { 
            String item = rs.getString("title"); 
            return item; 
        } 
    };

}

If you don't have a web application replace @Controller with @Service . 如果您没有Web应用程序,请将@Controller替换为@Service

Then rewrite your starter class. 然后重写你的入门级。

@SpringBootApplication
public class Starter {

    private static Logger logger;

    public static void main(String[] args) {

    //      SpringApplication.setWebEnvironment(false);

        ApplicationContext ctx = SpringApplication.run(Starter.class, args);

        LogbackConfigLoader lcl = new LogbackConfigLoader();
        if (lcl.init()) {
            logger = LoggerFactory.getLogger(Starter.class);
            logger.debug("Initialized....");
        }
        else{
            logger = LoggerFactory.getLogger(Starter.class);
        }

        MyController controller = ctx.getBean(MyController.class);
        logger.info(controller.getProva());

    }


}

Looks like you are also trying to circument spring boots config loading here? 看起来你也试图在这里装弹簧靴配置? Try to work with the framework not against it. 尝试使用框架而不是反对它。

If you don't have a web application don't include the spring-boot-starter-web in your dependencies and also make sure you don't have any other web related things in there. 如果您没有Web应用程序,请不要在依赖项中包含spring-boot-starter-web ,并确保您没有任何其他与Web相关的内容。 Spring Boot auto detects the web environment and tries to bootstrap classes for that, if those aren't there it will just run as a plain java application. Spring Boot会自动检测Web环境并尝试为其引导类,如果不存在,它将仅作为普通的Java应用程序运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM