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;
}
}
<?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来获取