reference: https://www.baeldung.com/spring-component-annotation
Before we can understand the value of @Component, we first need to understand a little bit about the Spring ApplicationContext.
Spring ApplicationContext is where Spring holds instances of objects that it has identified to be managed and distributed automatically. These are called beans
.
Some of Spring's main features are bean management and the opportunity for dependency injection.
Using the Inversion of Control principle, Spring collects bean instances from our application and uses them at the appropriate time. We can show bean dependencies to Spring without handling the setup and instantiation of those objects.
Dependency Injection (DI) encompasses three types: field DI, setter DI, and constructor DI. Among these, constructor DI is commonly preferred and widely used.
@Controller
public class MemberController {
private final MemberService memberService;
@Autowired
public MemberController(MemberService memberService){
this.memberService = memberService;
}
}
@Service
public class MemberService {
private final MemberRepository memberRepository;
@Autowired
public MemberService(MemberRepository memberRepository){
this.memberRepository = memberRepository;
}
...
}
@Repository
public class MemoryMemberRepository implements MemberRepository{
private static Map<Long, Member> store = new HashMap<>();
private static long sequence = 0L;
...
}
package hello.hellospring;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import hello.hellospring.service.MemberService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;`
@Configuration
public class SpringConfig {
@Bean
public MemberService memberService() {
return new MemberService(memberRepository());
}
@Bean
public MemberRepository memberRepository() {
return new MemoryMemberRepository();
}
}