Spring @Component 注解的使用

使用说明

这个注解用于声明当前的类是一个组件类,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");

猜你喜欢

转载自www.cnblogs.com/danhuang/p/12690359.html