2

Spring 5, Java 8 I have multiple configuration files, one of the configuration file has @Autowire dependency. it does not complain on run time and works fine but intellij warns can't find those beans.

wondering if thats ok to have @Autowire or @Inject in configuration class.

why i have it is b/c its my websocket configuration and my handlers need dependencies.

d-man
  • 57,473
  • 85
  • 212
  • 296
  • you mean like this? in general it's ok: https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch04s02.html but maybe you're doing something different? – Nathan Hughes Mar 18 '19 at 17:16

1 Answers1

3

It's OK.

@Configuration indicates that a class declares @Beans which might require dependencies. @Configuration itself is meta-annotated with @Component and "therefore may also take advantage of @Autowired/@Inject like any regular @Component".

I would recommend that you pass dependencies as method parameters rather than inject them into fields. It keeps the configuration class clear and emphasises the required dependencies for each @Bean method.

I prefer

class C {
    @Bean
    public A a(B b) { new A(b); }
}

to

class C {
    private final B b;        

    @Bean
    public A a() { new A(b); }
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142