Abhishek Galoda
Abhishek Galoda

Reputation: 3054

@Service/@Controller annotations creates a new bean without using @Bean annotation

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

Answers (2)

Abhishek Galoda
Abhishek Galoda

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

  • If the Class is in third party jar and you can not add @Service/@Controller annotations
  • If you want to add some custom logic inside the @Bean annotate methods

Upvotes: 3

robjwilkins
robjwilkins

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

Related Questions