Home > database >  Autowiring configuration class spring
Autowiring configuration class spring

Time:07-07

I'm wondering whether it's possible to autowire a class annotated with @Configuration into any annotated class (@Component, @SpringBootTest, etc)? I know it's possible between @Configuration classes, but I can't find a straight answer on if it's possible outside @Configuration classes (both test and non-test classes). Sample code to illustrate what I mean below:

@Configuration
public class Config {
    //Anything in here
}

//any non-Configuration annotation
public class Autowired {
    @Autowire
    Config config; //like this
}

CodePudding user response:

If you are looking at the source code of @Configuration annotation you can see it's annotated itself with @Component, making annotated classes with it also Spring components, so making them available for injection.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {

CodePudding user response:

What I guess you re looking for is

@Import(Any configuration.class)

  • Related