如何在Spring启动配置类中属性文件值

时间:2016-04-21 20:54:59

标签: java spring spring-boot

如何在Config类

中使用application.properties文件

application.properties

datasource.username =测试

Config.class

 @Configuration
 @EnableTransactionManagement
 @EnableJpaRepositories(
    entityManagerFactoryRef = "abcFactory", 
    transactionManagerRef = "abcmanager",
    basePackages = { "com.emp.repository" }) 

    public class EmpConfig {

        @Value("${datasource.username}")
        String username;

        @Bean(name = "empDataSource")      
        public DataSource empDataSource(String url, String userName, String pwd) {        
         DriverManagerDataSource dataSource = new DriverManagerDataSource();
         dataSource.setDriverClassName("XXX");
         dataSource.setUrl(url);
         dataSource.setUsername(userName);
         dataSource.setPassword(pwd);         
         return dataSource;        

        }


    }

如何将属性传递到用户名设置字段。

1 个答案:

答案 0 :(得分:1)

取决于您初始化应用的方式,但通常会添加类似

的内容
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
@ComponentScan
@SpringBootApplication
@EnableTransactionManagement

确保你的配置中有其中一个

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

然后你可以访问这样的值

@Value("${datasource.username}")
@NotNull //optional
String username;