Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowire a string from Spring @Configuration class?

Tags:

java

spring

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;
}
like image 879
css Avatar asked Aug 20 '14 17:08

css


People also ask

Can you Autowire in a configuration class?

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.

Can we Autowire string in Spring?

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.

What is the use of @configuration in Spring?

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.

Does @configuration create a bean?

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.


1 Answers

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;
}
like image 148
Ricardo Veguilla Avatar answered Sep 16 '22 13:09

Ricardo Veguilla