Spring属性未加载

时间:2016-04-25 21:57:22

标签: java spring spring-boot

我第一次使用Spring Boot并使用xml less config。

尝试在我的bean类中添加属性文件值,但获取null值。这是我的代码:

config.java:

import java.sql.SQLException;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import oracle.jdbc.pool.OracleDataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.stereotype.Component;

@Configuration
@ComponentScan
@PropertySource("classpath:application.properties")
public class Config {

    @Autowired
    private static SpringAppProp springAppProp;





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

    @Value("${driverClassName}")
    private static String driverClassName;

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

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

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

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

    @Value("${dbPort}")
    private static int dbPort;

    @Value("${dbServiceName}")
    private static String dbServiceName;

    @Value("${dbServer}")
    private static String dbServer;



    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
    @Bean(name = "DataSource")
    public static BasicDataSource dataSource() throws SQLException {
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setUrl(url);
        basicDataSource.setDriverClassName(driverClassName);
        basicDataSource.setInitialSize(initialSize);
        basicDataSource.setMaxTotal(maxActive);
        basicDataSource.setMaxIdle(5);
        basicDataSource.setMinIdle(0);
        basicDataSource.setMaxWaitMillis(15000);
        return basicDataSource;
      }

}

application.properties:

server.port=8080
driverClassName=oracle.jdbc.driver.OracleDriver
username=XXXX
password=XXXX
initialSize=10
maxActive=20
dbPort=XXX
dbServiceName=xxxx
dbServer=xxxxxx
url=jdbc:oracle:thin@//xxxxx

有人可以看到并让我知道我在这里做错了什么..

1 个答案:

答案 0 :(得分:2)

从您使用static注释的字段中删除Value

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

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

由于你使用的是Spring Boot,因此不需要@PropertySource

更新正如M. Deinum所说,最好完全放弃配置类,并在spring.datasource.*中使用application.properties属性。