使用說明
這個注解用於聲明當前的類是一個組件類,Spring 會通過類路徑掃描來自動偵測和自動裝配這些組件,創建一個個 bean 后,注冊到 Spring 容器中。
帶 @Component 注解的類和自動創建的 bean 之間存在隱式的一對一映射關系。由於只需要聲明一個注解,其他過程都是自動化的,所以對 bean 的創建過程可控程度較低。
該注解相當於:
<bean id="useService" class="com.test.service.UserServiceImpl"/>
普通組件
@Component
public class UserServiceImpl implements IUserService {
private String name;
// getter&&setter...
}
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
IUserService service = (IUserService)context.getBean(UserServiceImpl.class);
命名組件
@Component(value = "userService")
public class UserServiceImpl implements IUserService {
private String name;
// getter&&setter...
}
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
IUserService service = (IUserService)context.getBean("userService");