Junior — Middle
How to determine that the @Bean annotation is used for a property inside a class during Spring configuration?
sobes.tech AI
Answer from AI
The @Bean annotation in Spring is typically applied to methods within a class marked as @Configuration. It indicates that the method returns an object that should be registered in the Spring context as a bean.
If @Bean is used for a property (field) inside a class, this is not standard practice and will not work, as @Bean is intended for methods.
Correct usage:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
If you need to inject a dependency into a field, use @Autowired or constructor injection, not @Bean.