如何在spring-boot中通过application.properties创建配置类?

时间:2020-04-22 11:40:53

标签: java spring spring-boot spring-mvc

我有两个问题。

首先,我在spring-boot中测试了数据库连接,如下所示。

@RunWith(SpringJUnit4ClassRunner.class)
public class OracleConnectionTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(OracleConnectionTest.class);

    private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
    private static final String USER = "user1";
    private static final String PW = "user1";

    @Test
    public void testConnection() throws ClassNotFoundException {
        Class.forName(DRIVER);

        try (Connection connection = DriverManager.getConnection(URL, USER, PW)) {
            LOGGER.info(String.valueOf(connection));
        } catch (SQLException e) {
            LOGGER.error(String.valueOf(e));
        }
    }
}

但是我想将数据库信息分成application.properties文件(resources / application.properties)。因此,我需要制作如下的JdbcConfig文件(java bean)(带有测试代码)。

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class JdbcConfig {
    @Value("${driver-class-name}")
    private String driverClassName;
    @Value("${url}")
    private String url;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;

    @Override
    public String toString() {
        return "JdbcConfig[" +
                "driverClassName=" + driverClassName
                + ", url=" + url
                + ", username=" + username
                + ", password=" + password
                + "]";
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {JdbcConfig.class})
public class OracleConnectionTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(OracleConnectionTest.class);

    @Autowired
    private JdbcConfig jdbcConfig;

    @Test
    public void testConnection() throws ClassNotFoundException {
        LOGGER.info("Test: {}", jdbcConfig.toString());

        Class.forName(jdbcConfig.getDriverClassName());

        try (Connection connection = DriverManager.getConnection(jdbcConfig.getUrl(), jdbcConfig.getUsername(), jdbcConfig.getPassword())) {
            LOGGER.info(String.valueOf(connection));
        } catch (SQLException e) {
            LOGGER.error(String.valueOf(e));
        }
    }
}

但是,我在运行NullPointerException(JdbcConfig)时遇到了testConnection()。因此,我必须像这样修改JdbcConfig类。

@Getter
@Setter
@Component
@PropertySource("classpath:application.properties")
public class JdbcConfig {
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @Override
    public String toString() {
        return "JdbcConfig[" +
                "driverClassName=" + driverClassName
                + ", url=" + url
                + ", username=" + username
                + ", password=" + password
                + "]";
    }
}

我不明白为什么@Configuration@ConfigurationProperties注释不适用。

第二,我认为spring-boot将通过读取DataSource(javax.sql.DataSource)自动创建application.properties。例如,我的朋友成功测试未创建DataSource bean(class)。但是我遇到了如下错误。

Unsatisfied dependency expressed through field 'ds'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available

所以我必须创建DataSource bean。我不知道为什么我朋友的代码不像我一样不创建bean(DataSource)就能自动工作。我的代码如下。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = DataSourceConfig.class)
public class DataSourceTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceTest.class);

    @Autowired
    private DataSource ds;  // DataSource & DriverManagerDataSource

    @Test
    public void testConnection() throws Exception {
        try (Connection con = ds.getConnection()) {
            LOGGER.info(String.valueOf(con));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
@Configuration
@Import(JdbcConfig.class)
public class DataSourceConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceConfig.class);

    @Bean
    public DataSource dataSource(JdbcConfig jdbcConfig) {
        LOGGER.debug("Test: {}", jdbcConfig.toString());
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(jdbcConfig.getDriverClassName());
        dataSource.setUrl(jdbcConfig.getUrl());
        dataSource.setUsername(jdbcConfig.getUsername());
        dataSource.setPassword(jdbcConfig.getPassword());
        return dataSource;
    }
}

感谢您阅读我的长篇文章。


添加属性文件(application.properties)

# JSP
spring.mvc.view.prefix = /WEB-INF/jsp/
spring.mvc.view.suffix = .jsp

# language setting
spring.http.encoding.charset = UTF-8
spring.http.encoding.enabled = true
spring.http.encoding.force = true

# Database Info
spring.datasource.driver-class-name = oracle.jdbc.driver.OracleDriver
spring.datasource.url = jdbc:oracle:thin:@127.0.0.1:1521:orcl
spring.datasource.username = user1
spring.datasource.password = user1

1 个答案:

答案 0 :(得分:0)

所有你需要的东西:

@Getter
@Setter
@ConfigurationProperties(prefix = "spring.datasource")

+
@EnableConfigurationProperties(YourPropertiesClass.class)在任何配置类上

如果您正在使用Spring Boot 2. +,那么这甚至是多余的 有关更多信息,请参见release notes


现在需要添加@ConfigurationPropertiesScan