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;
}
The configuration classes themselves are registered as beans to the Spring container. That means, we can do whatever we do with a normal spring bean. For example we can use @Autowire to have Spring to perform DI in them.
The Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans. This is called Spring bean autowiring.
Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.
When @Configuration classes are provided as input, the @Configuration class itself is registered as a bean definition, and all declared @Bean methods within the class are also registered as bean definitions.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With