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的注册文件中添加设置Spring要自动扫描的包



	
	
	
	
	 

我们想要获取学生类,将类名的首字母小写,然后使用getBean();的方法来获取

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

同时也可以修改检测的组件名,如@Componet("studentBean"),这样在获取的时候就可以使用studentBean来获取




你可能感兴趣的:(Spring,Spring)