Spring攻略筆記-4 掃描組件

Spring提供一個強大的功能--組件掃描,這個功能能夠利用特殊的典型化註解,從classpath中自動掃描,檢測盒實例化你的組件。指示Spring管理組件的基本註解是@Componet。其他特殊的典型化包括@Repository持久層,@Service服務層,@Controller表現層。


比如,有個學生類,類中有個班級的屬性,我們將其設置爲自動注入,使用掃描組件的方式。

班級類,將其設爲自動掃描,就要在類前加上@Componet註解,爲了方便,設置默認班級名

package com.lkt.entity;

import org.springframework.stereotype.Component;

@Component
public class Clazz {
	
	private String className="一班";

	public String getClassName() {
		return className;
	}

	public void setClassName(String className) {
		this.className = className;
	}
	
	
}
學生類,將其設爲自動掃描,就要在類前加上@Componet註解,將班級屬性設爲自動注入,使用@Autowired註解

package com.lkt.entity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;
@Component
public class Student {
	private String userName;
	private String password;
	private String realName;
	@Autowired
	private Clazz clazz;
	
	public Clazz getClazz() {
		return clazz;
	}
	public void setClazz(Clazz clazz) {
		this.clazz = clazz;
	}
	public Student() {
		// TODO Auto-generated constructor stub
	}
	public Student(String userName,String password,String realName) {
		this.userName=userName;
		this.password=password;
		this.realName=realName;
	}
	@Override
	public String toString() {
		
		return "userName:"+userName+"  password:"+password+"  realName:"+realName;
	}
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getRealName() {
		return realName;
	}
	public void setRealName(String realName) {
		this.realName = realName;
	}
}


最後需要在Spring的註冊文件中添加<context:componet-scan base-package=''>設置Spring要自動掃描的包

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
						http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
						http://www.springframework.org/schema/context
						http://www.springframework.org/schema/context/spring-context-3.0.xsd
						">
	<!-- 添加註解功能 -->
	<context:annotation-config/>
	<!-- 添加自動掃描 -->
	<context:component-scan base-package="com.lkt.entity"></context:component-scan>
	 
</beans>

我們想要獲取學生類,將類名的首字母小寫,然後使用getBean();的方法來獲取

Student student=(Student)ac.getBean("student");

同時也可以修改檢測的組件名,如@Componet("studentBean"),這樣在獲取的時候就可以使用studentBean來獲取




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章