Wouter Vandenputte
Wouter Vandenputte

Reputation: 2093

Spring @Value does not load properties

I have two classes which both use configuration properties.

This one loads

package com.cegeka.campus;

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

But this one returns null:

package com.cegeka.campus;

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

Our main class looks like this:

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

Why can't I load backend.authorize.url? The @Value simply doesn't inject.

The properties file (application.yml) looks like this:

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

Upvotes: 2

Views: 2490

Answers (2)

Mikhail Potter
Mikhail Potter

Reputation: 530

I can see two issues in the class AuthHelper:

  1. AuthHelper should be a Spring managed bean and have @Component annotation.

  2. Field redirectUrl is static and cannot be injected. The solution is either make the field non static or

private static String redirectUrl;

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

Upvotes: 2

hicham abdedaime
hicham abdedaime

Reputation: 366

add this method and try again :

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

Upvotes: 0

Related Questions