Reputation: 3054
I have a class which I have annotated with @Service @Scope
@Slf4j
@Service
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ProductDataModel {
@Value("${message}")
private String message;
The above code seems to be creating a bean for ProductDataModel, without using the @Bean annotation.
I am using @Autowired ProductDataModel productDataModel
in my code, and the dependency productDataModel is not null, when used with above piece of Code.
How come the above code is creating bean ??
Ideally, I would have expected bean to created only when I use the below code
//I am not using this piece of code in my program., for reference only
@Configuration
public class OSCConfig {
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
ProductDataModel productDataModel(){
return new ProductDataModel();
}
Can someone explain the difference between 2 pieces of code and when to use which one.
Upvotes: 1
Views: 1793
Reputation: 3054
As @M. Deinum pointed out that we don't need to specify @Bean for each class when we declare @Service or @Controller annotation they are picked up by Spring Container if component-scanning is enabled for that package.
So good use case for using @Bean could be that
Upvotes: 3
Reputation: 5652
The @Service annotation is picked up by Spring when scanning for objects to create (as part of a package scan). It is an specialisation of the spring @Component annotation, but doesn't really add much other than providing an indication to users about its intended purpose. The @Controlller annotation is similar, but the bean created has specific characteristics.
The @Bean annotation as you have used it is also used when creating objects, and in this context it is on a method in a Configuration class, therefore the bean created is of the type returned by the method.
Upvotes: 0