Autowire string from Spring @Configuration class?

I want to centralize access to all my property values ​​so that I can do things like make sure everyone uses the same name for properties, the same default values, etc. I created a class to centralize all of this, but I'm not sure how classes that need access to these values ​​should get them, since you cannot autowire Strings.

My class looks something like this:

@Configuration public class SpringConfig { @Autowired @Value("${identifier:asdf1234}") public String identifier; } 

Where can I use it in several classes

 public class Foo { @Autowired private String theIdentifier; } public class Bar { @Autowired private String anIdentifier; } 
+6
source share
3 answers

Another solution would be to create a Spring bean with all your configuration and execute its autwire:

 @Component public class MyConfig { @Value("${identifier:asdf1234}") public String identifier; public String getIdentifier() { return identifier; } } 

And in other classes:

 public class Foo { @Autowired private MyConfig myConfig; public void someMethod() { doSomething(myConfig.getIdentifier()); } } 
+5
source

Initialized a bean string based on a property:

 @Configuration public class SpringConfig { @Bean public String identifier(@Value("${identifier:asdf1234}") identifier) { return identifier; } } 

Then enter its bean using the Spring SpEL expression beanName "#{beanName} in the @Value annotation

 @Component public class Foo { @Value("#{identifier}") private String oneIdentifier; } public class Bar { @Value("#{identifier}") private String sameIdentifier; } 
+4
source

In my opinion, there is no clean solution. The simplest thing I can think of is to use the static constant String field, which contains the property placeholder.

 public final class Constants { private Constants() {} public static final String PROPERTY_NAME= "${identifier.12345}"; } 

and all @Value annotations use it

 public class Foo { @Value(Constants.PROPERTY_NAME) private String theIdentifier; } public class Bar { @Value(Constants.PROPERTY_NAME) private String anIdentifier; } 

Now, if you ever need to change the name of a property, you only need to change it in Constants . But be sure to recompile everything.

+1
source

Source: https://habr.com/ru/post/974113/


All Articles