Java – Autowire a string from Spring @Configuration class

javaspring

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

My class is something like this:

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

Where I might use it in multiple classes

public class Foo {
    @Autowired 
    private String theIdentifier;
}

public class Bar {
    @Autowired 
    private String anIdentifier;
}

Best Solution

Initialized a String bean based on the property:

@Configuration
public class SpringConfig {

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

Then inject it by bean name using Spring's SpEL beanName expression "#{beanName} in a @Value annotation

@Component
public class Foo {
    @Value("#{identifier}")
    private String oneIdentifier;
}

public class Bar {
   @Value("#{identifier}")
   private String sameIdentifier;
}