Spring Boot: How to externalize JDBC datasource configuration?

后端 未结 2 841
别那么骄傲
别那么骄傲 2020-12-31 09:53

I have following Spring Boot controller code that works. (Some sensitive text was replaced)

package com.sample.server;

import java.sql.ResultSet;
import jav         


        
2条回答
  •  独厮守ぢ
    2020-12-31 10:04

    Change your controller to the following

    @RestController
    public class DetailReportController {
    
        @Autowired
        private JdbcTemplate jt;
    
        @RequestMapping(value="/report/detail", method=RequestMethod.GET)
        public List detailReport() {
            List results = jt.query(
                "select NID, SCode, SName from UFGroup",
                new RowMapper(){
                    @Override
                    public UFGroup mapRow(ResultSet rs, int rowNum) throws SQLException {
                        return new UFGroup(rs.getInt("NID"), rs.getString("SCode"), rs.getString("SName"));
                    }
                });
            return results;
        }
    
        private static class UFGroup
        {
            public int nid;
            public String scode;
            public String sname;
    
            public UFGroup(int nid, String scode, String sname)
            {
                this.nid = nid;
                this.scode = scode;
                this.sname = sname;
            }
        }
    }
    

    In src/main/resources add an application.properties with the following

    spring.datasource.driverClassName=net.sourceforge.jtds.jdbc.Driver
    spring.datasource.url=jdbc:jtds:sqlserver://111.11.11.11/DataBaseName
    spring.datasource.username=sa
    spring.datasource.password=password
    

    And simply start your application. No xml needed. Spring boot will create the DataSource and will add a default JdbcTemplate instance.

    Tip: Remove the dependency for org.apache.commons.dbcp spring-boot will give you the newer (and IMHO better) tomcat connection pool (which despite the name can be used entirely on its own).

提交回复
热议问题