使用说明

这个注解用于声明当前的类是一个组件类,Spring 会通过类路径扫描来自动侦测和自动装配这些组件,创建一个个 bean 后,注册到 Spring 容器中。

带 @Component 注解的类和自动创建的 bean 之间存在隐式的一对一映射关系。由于只需要声明一个注解,其他过程都是自动化的,所以对 bean 的创建过程可控程度较低。

该注解相当于:

<bean />

普通组件

@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");

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2018-04-25
  • 2021-06-12
  • 2020-10-06
  • 2022-12-23
  • 2021-11-20
猜你喜欢
  • 2022-01-20
  • 2021-08-28
  • 2022-12-23
  • 2022-12-23
  • 2021-04-30
  • 2021-05-29
  • 2022-12-23
相关资源
相似解决方案