@Component vs @Bean

@Component

@Component and its specializations (@Controller, @Service and @Repository) allow for auto-detection using classpath scanning.

@Component vs @Bean

Can we use just @Component for all the components for auto scanning?

Yes, you can, and Spring will auto scan all your components with @Component annotated.But it is not a good practice. For readability, you should always declare @Repository,@Service or @Controller for a specified layer.

@Bean

@Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically like we did with @Controller. It decouples the declaration of the bean from the class definition and lets you create and configure beans exactly how you choose.

Note: @Bean can not be placed at the class level. @Bean methods are declared within @Configuration classes.

Person.java 

package com.spring.example.bean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Person {

@Autowired
private Address address;

public Address getAddress() {
return address;
}

}

Address.java

package com.spring.example.bean;

public class Address {

private String city;

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

}

BeanConfiguration.java

package com.spring.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.spring.example.bean.Address;

@ComponentScan(basePackages = “com.spring.example.bean”)
@Configuration
public class BeanConfiguration {

@Bean
public Address address() {
Address address = new Address();
address.setCity(“Mumbai”);
return address;
}

}

TestBeanLifeCycle.java

package com.spring.example.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.spring.example.bean.Person;
import com.spring.example.config.BeanConfiguration;

public class TestBeanLifeCycle {

public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(BeanConfiguration.class);
Person person = context.getBean(Person.class);
System.out.println(person.getAddress().getCity());
context.close();
}

}

Output
Mumbai

Related Articles

Important Spring Topic Links

Basic Spring Annotations

Leave a Reply

Your email address will not be published. Required fields are marked *