java - @Value 注释未正确设置

标签 java spring annotations

这是我的应用程序:

public static void main( String[] args ) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);

    //run the importer
    final ImportNewOrders importer = (ImportNewOrders) ApplicationContextProvider.getApplicationContext().getBean("importNewOrders");
    importer.run();
    //importer.runInBackground();
}

这是我的配置:

@Configuration
@ComponentScan(basePackages = {
        "com.production"
})
@PropertySource(value = {
        "classpath:/application.properties",
        "classpath:/environment-${MY_ENVIRONMENT}.properties"
})
@EnableJpaRepositories("com.fettergroup.production.repositories")
@EnableTransactionManagement
public class Config {

    .... skipping things that aren't relevant

    @Bean
    public ImportNewOrders importNewOrders() {
        return new ImportNewOrders();
    }

这是我的类(class)...

@Component
public class ImportNewOrders implements Task {

    private final static Logger logger = Logger.getLogger(ImportNewOrders.class.getName());

    @Autowired
    private OrderService orderService;

    @Autowired
    private ImportOrderRequest importOrderRequest;

    @Value("${api.user}")
    private String apiUser;

    @Value("${api.password}")
    private String apiPassword;

    @Value("${api.orders.pingFrequency}")
    private String pingFrequency;

最后是application.properties:

# ------------------- Application settings -------------------

#Base URL to the API application
api.baseUrl=http://localhost:9998

#Unique token used to authenticate this vendor
api.vendor.token=asdf

#API credentials
api.user=myuser
api.password=mypassword

#How often to check for new orders; frequency is in seconds
api.orders.pingFrequency=60

这在一两个小时前有效,现在它决定不喜欢这些值。我不知道为什么。在我看来一切都是正确的。

更新

@Configuration
@ComponentScan(basePackages = {
        "com.production"
})
@PropertySource(value = {
        "classpath:/application.properties",
        "classpath:/environment-${MY_ENVIRONMENT}.properties"
})
@EnableJpaRepositories("com.production.repositories")
@EnableTransactionManagement
public class Config {
    @Value("${db.url}")
    private static String PROPERTY_DATABASE_URL;

    @Bean
    public DataSource dataSource() {
        MysqlDataSource dataSource = new MysqlDataSource();

        dataSource.setUrl(PROPERTY_DATABASE_URL); //is null
        /*dataSource.setUser(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USER));
        dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));*/

        return dataSource;
    }

    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer () {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

最佳答案

您的属性文件由您的@Configuration 找到,并由于@PropertySource 将其用于该类中的数据库属性。但 @Value 字段和 ${} 评估需要的不仅仅是这些。

来自Javadoc for @PropertySource

In order to resolve ${...} placeholders in definitions or @Value annotations using properties from a PropertySource, one must register a PropertySourcesPlaceholderConfigurer. This happens automatically when using in XML, but must be explicitly registered using a static @Bean method when using @Configuration classes. See the "Working with externalized values" section of @Configuration Javadoc and "a note on BeanFactoryPostProcessor-returning @Bean methods" of @Bean Javadoc for details and examples.

所以声明一个

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer p = new PropertySourcesPlaceholderConfigurer();
    p.setLocation(new ClassPathResource("your properties path"));
    // other properties
    return p;
}

在你的配置类中,或者正如ach在注释中恰当提到的那样,如果你使用@PropertySource,你可以完全省略setLocation:

@Configuration
@PropertySource(value="classpath:your_file.properties")
public class MyConfiguration{

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()    {
        PropertySourcesPlaceholderConfigurer p = new PropertySourcesPlaceholderConfigurer();
    return p;
    }
}

当您拥有 PropertySourcesPlaceholderConfigurer 时,您不需要环境

In most cases, however, application-level beans should not need to> interact with the Environment directly but instead may have to have ${...} property values replaced by a property placeholder configurer such as PropertySourcesPlaceholderConfigurer, which itself is EnvironmentAware and as of Spring 3.1 is registered by default when using < context:property-placeholder/>.

关于java - @Value 注释未正确设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15395123/

相关文章:

java - Spring 数据 JPA : Creating Specification Query Fetch Joins

java - 从 android 应用程序转换的黑莓 10 应用程序的 javascript 调用 java 函数

jpa - JPA @Entity 注解的确切含义是什么?

iphone - 更改自定义注释标签而不将其从 iPhone 中的 map 中删除

java - 为什么我可以从 getClass().getResource() 获取有效的 url,但返回的 url 创建了一个不存在的文件

java - 使用 Eclipse BIRT 报告引擎在 Web 应用程序中生成 Word 文档

java - Spring MVC(异步)与 Spring WebFlux

java - 如何正确使用 JTI 声明和 JWT 来防止重放攻击?

java - 使用 CrudRepository 的自定义查询

java - @OneToMany mappedBy 映射到 _____