【问题标题】:Spring @Value does not load propertiesSpring @Value 不加载属性
【发布时间】:2017-05-31 13:51:39
【问题描述】:

我有两个类都使用配置属性。

这个加载

package com.cegeka.campus;

@RestController
@RequestMapping("api/outlook")
public class OutlookController
{
    @Value("${frontend.url}")
    private String frontendUrl;
    .....
}

但是这个返回null:

package com.cegeka.campus;

public class AuthHelper
{
    @Value("${backend.authorize.url}")
    private static String redirectUrl;
    ...
}

我们的主类如下所示:

@SpringBootApplication
@ComponentScan("com.cegeka.campus")
@EnableJpaRepositories("com.cegeka.campus")
@EntityScan("com.cegeka.campus")
public class CampusApplication extends SpringBootServletInitializer
{
    public static void main(String[] args)
    {
        SpringApplication.run(CampusApplication.class, args);
    }
}

为什么我无法加载 backend.authorize.url? @Value 根本不会注入。

属性文件 (application.yml) 如下所示:

frontend:
  url: http://hi02549:8080/courseka
backend:
  authorize:
    url: http://hi02549:8080/campus/api/outlook/authorize

【问题讨论】:

    标签: java spring properties configuration


    【解决方案1】:

    我可以在 AuthHelper 类中看到两个问题:

    1. AuthHelper 应该是 Spring 托管的 bean 并具有 @Component 注释。

    2. 字段redirectUrl 是静态的,无法注入。解决方案是使字段非静态或

    private static String redirectUrl;
    
    @Value("${backend.authorize.url}")
    public void setRedirectUrl(String url) {
        redirectUrl = url;
    }
    

    【讨论】:

    • 你的先生,是个英雄。
    【解决方案2】:

    添加此方法并重试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-15
      • 2016-12-27
      • 2017-03-29
      • 1970-01-01
      • 2020-05-03
      • 2014-12-21
      • 1970-01-01
      • 2011-07-13
      相关资源
      最近更新 更多