【问题标题】:How to property file value in Spring boot config class如何在 Spring Boot 配置类中属性文件值
【发布时间】:2016-08-15 06:50:10
【问题描述】:

如何在 Config 类中使用 application.properties 文件

application.properties

datasource.username=test

配置类

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

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

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    取决于你如何初始化你的应用程序,但通常你会放类似

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

    确保您的配置中有其中之一

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

    然后你可以访问这样的值

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

    【讨论】:

    • 你不需要@EnableAutoConfiguration@ComponentScan@PropertySource("classpath:application.properties"),因为@SpringBootApplication已经包含了前两个。 application.properties 默认会扫描属性,因此您无需将其添加为属性源。如果你的 pom 中有 spring boot starter,你也不需要PropertySourcesPlaceholderConfigurer
    • 如果我使用以下,它不工作。 @Value("${datasource.username}") @NotNull //可选字符串用户名;
    • 这里:stackoverflow.com/questions/36635163/… 您可以找到一个具有内部和外部属性的工作 Spring Boot 项目的示例。 @RahulSharma 在他的所有 cmets 中都是正确的。
    • @Mukti 你需要添加代码让我们看看发生了什么
    • @RahulSharma,我已经更新了上面的代码,仍然在使用@Value("${datasource.username}")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 2017-08-18
    • 2020-12-23
    • 1970-01-01
    • 2021-02-16
    • 2021-11-27
    相关资源
    最近更新 更多