0

Hi am using spring 2.4 version and feign cloud from spring cloud

but i getting stuck that am not able to use some constant value inside @bean method when i reading from property file

@Configuration
public class FeignClientConfiguration {

    @Value("${app.basic.auth.username}")
    private static String userName;

    @Value("${app.basic.auth.password}")
    private static String password;


    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        // return new BasicAuthRequestInterceptor("admin", "admin");
        return new BasicAuthRequestInterceptor(userName, password);
    }
}

But i while provides value in like this i will work fine

return new BasicAuthRequestInterceptor("admin", "admin");

Am not sure why this is not working can you please suggest me any way to achieve this

harkesh kumar
  • 833
  • 2
  • 13
  • 35

2 Answers2

1

You should seperate your configuration class and the basicAuthRequestInterceptor method.

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "app")    
public class LoginProperties {

    private String username;
    private String password;    
}

In your properties file,have the below:

app.username = user
app.password = 123

Then in your controller/service class, do the following.

@Autowired
private LoginProperties loginProperties; 

public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor(loginProperties.getUserName(), loginProperties.password());
    }
Rahul SK
  • 350
  • 3
  • 23
0

Best way to find out is create a simple @PostConstruct method and print both the values..if they are null then that means the spring was not able to resolve those property values.

Make sure you've initialized the properties using PropertyPlaceholderConfigurer and path to property file is correct (even if relative to classpath).

Keep your eyes on logs and don't ignore any exception.