当前位置: 移动技术网 > IT编程>开发语言>Java > Spring @Component 注解的使用

Spring @Component 注解的使用

2020年04月13日  | 移动技术网IT编程  | 我要评论

使用说明

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网