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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM