2

Is there an option to insert property on interface field? I tried something like this, but it didn't work.

public interface ServicePathsConfig {
    @Value("${default-connection-timeout}")
    int DEFAULT_CONNECT_TIMEOUT = 1000;
}

I tried to make default setter with @PostConstruct, same result. Any ideas how can I inject property to interface field?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
NOXYEES
  • 41
  • 3
  • 3
    You cannot inject into an interface field. "fields" in interfaces are actually `public static final` and you cannot use `@Value` on a `static` field. – M. Deinum Dec 14 '20 at 09:05
  • Does this answer your question? [Spring: How to inject a value to static field?](https://stackoverflow.com/questions/7253694/spring-how-to-inject-a-value-to-static-field) – Joe Jan 07 '21 at 12:52

3 Answers3

0

You can open config java class with this codes. @Configuration @ComponentScan("com.??") @PropertySource("classpath:(??.properties"))

And put default-connection-tiemout to another new property file without int. But you cant inject this to interface you need to inject some java class.

Burak S.
  • 1
  • 2
0
java class:

@Component
public class blabla implements blabla1 {

    @Value("${default-connection.timeout}")
   int default-connection;

--------------
interface
public interface blabla1 {
}

-------------
file:
Timeout.properties
default-connection.timeout=1000

------------------
java class:

@Configuration
@ComponentScan("com.(your package name)")
@PropertySource("classpath:connection.properties")
public class TimeoutConfig {


}
Burak S.
  • 1
  • 2
0

As a workaround, in some cases you can turn your interface into an abstract class, and then it is possible:

public abstract class ServicePathsConfig {
    @Value("${default-connection-timeout:1000}")
    protected int defaultConnectTimeout;

    public abstract void someMethod();
}
Honza Zidek
  • 9,204
  • 4
  • 72
  • 118