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