如何在spring-boot中用application.properties制作config类?

我有两个问题。

首先,我在spring-boot中测试了db连接,如下图所示。

@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));
        }
    }
}

但是我想把DB信息分离到application.properties文件(resourcesapplication.properties)中去,所以我需要制作JdbcConfig文件(java Bean)。所以我需要制作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)的情况下测试成功。但是我遇到了一个错误,就像下面的错误一样,所以我必须创建DataSource bean。

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

解决方案:

所有你需要的。

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

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

如果你使用的是Spring Boot 2.+,那么即使是这个也是多余的。发行说明 更多

需要增加 @ConfigurationPropertiesScan 现在

给TA打赏
共{{data.count}}人
人已打赏
解决方案

搜索内部内容字段

2022-4-20 4:00:07

解决方案

BLE数据传输是否需要配对(无配对的BT数据传输)

2022-4-20 4:00:09

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索